Question

In: Computer Science

Research "Const Correctness" and answer the following questions: Given: class SimpleClass { private: int _x; public:...

Research "Const Correctness" and answer the following questions:

Given:

class SimpleClass
{
    private:
    int _x;

    public:
    SimpleClass(int x) : _x(x){}

    int getX() const
    {
        return _x;
    }

    void setX(int newX)
    {
        _x = newX;
    }

    void displayDataWithCustomMessage(const string &customMessage)
    {
        cout<<"Data: "<<_x<<endl;
        cout<<"Custom Message: "<<customMessage<<endl;
    }
};
  1. What is the usefulness of the "const" keyword in the definition of the "getX" member function?
  2. What is the usefulness of the "const" keyword in the definition of the "displayDataWithCustomMessage" member function?
  3. Why shouldn't the "const" keyword be used in the definition of the "setX" member function?

Solutions

Expert Solution

1. What is the usefulness of the "const" keyword in the definition of the "getX" member function?

The const keyword is used in the definition of getX() member function to allow it to be called by const or non const object from main method. If const keyword is not used , we cannot call this function getX() from const object.

2. What is the usefulness of the "const" keyword in the definition of the "displayDataWithCustomMessage" member function?

const SimpleClass t(10); // const object
   cout<<t.getX();
   t.displayDataWithCustomeMessage(" is verified"); // will generate compilation error.

3. Why shouldn't the "const" keyword be used in the definition of the "setX" member function?

Set methods are used to change the values of variables . But const methods do not allow to change the variable values. So const keyword should not be used with setX();

#include <iostream>
using namespace std;

class SimpleClass
{
private:
int _x;

public:
SimpleClass(int x) : _x(x){}

int getX() const // if we don't use const method , const objects cannnot call this function
{
return _x;
}

void setX(int newX)
{
_x = newX;
}

void displayDataWithCustomMessage(const string &customMessage)
{
cout<<"Data: "<<_x<<endl;
cout<<"Custom Message: "<<customMessage<<endl;
}
};

int main() {
  
   // both const and non const objects can call const functions
   const SimpleClass t(10); // const object
   cout<<t.getX();
   t.displayDataWithCustomeMessage(" is verified"); // will generate compilation error.
  
  
   SimpleClass t1(10); // non const object
   cout<<t1.getX();
   t1.displayDataWithCustomeMessage(" is verified");
  
   return 0;
}

Do ask if any doubt. Please upvote.


Related Solutions

#include<iostream> using namespace std; class point{ private: int x; int y; public: void print()const; void setf(int,...
#include<iostream> using namespace std; class point{ private: int x; int y; public: void print()const; void setf(int, int); }; class line{ private: point ps; point pe; public: void print()const; void setf(int, int, int, int); }; class rectangle{ private: line length[2]; line breadth[2]; public: void print()const; void setf(int, int, int, int, int, int, int, int); }; int main(){ rectangle r1; r1.setf(3,4,5,6, 7, 8, 9, 10); r1.print(); system("pause"); return 0; } a. Write function implementation of rectangle, line and point. b. What is...
public class SinglyLikedList {    private class Node{        public int item;        public...
public class SinglyLikedList {    private class Node{        public int item;        public Node next;        public Node(int item, Node next) {            this.item = item;            this.next = next;        }    }       private Node first;    public void addFirst(int a) {        first = new Node(a, first);    } } 1. Write the method add(int item, int position), which takes an item and a position, and...
public class Date { private int dMonth; //variable to store the month private int dDay; //variable...
public class Date { private int dMonth; //variable to store the month private int dDay; //variable to store the day private int dYear; //variable to store the year //Default constructor //Data members dMonth, dDay, and dYear are set to //the default values //Postcondition: dMonth = 1; dDay = 1; dYear = 1900; public Date() { dMonth = 1; dDay = 1; dYear = 1900; } //Constructor to set the date //Data members dMonth, dDay, and dYear are set //according to...
public class SumMinMaxArgs { private int[] array; // You will need to write the following: //...
public class SumMinMaxArgs { private int[] array; // You will need to write the following: // // 1. A constructor that takes a reference to an array, // and initializes an instance variable with this // array reference // // 2. An instance method named sum, which will calculate // the sum of the elements in the array. If the array // is empty (contains no elements), then this will // will return 0. You will need a loop for...
Given: class Monster {     private:     string name;     int dangerLevel;     public:     Monster(sting, int);     virtual void hunt()
Given: class Monster {     private:     string name;     int dangerLevel;     public:     Monster(sting, int);     virtual void hunt() = 0;     virtual void fight(Monster&);     string getName() const; }; class GiantMonster : public Monster {     protected:         int height;          public:         GiantMonster(string, int, int);         virtual void trample(); }; class Dinosaur : public GiantMonster {     public:     Dinosaur(string, int, int);     void hunt();     void roar(); }; class Kraken : protected GiantMonster {     public:     Kraken(string, int, int);     virtual void hunt();     void sinkShip(); }; Indicate if the code snippets below are...
class A { public: //constructors // other members private: int a; int b; }; Give declatations...
class A { public: //constructors // other members private: int a; int b; }; Give declatations of operator functions for each of the following ways to overload operator + You must state where the declatation goes, whether within the class in the public or private section or outside the class. The operator + may be overloaded. a) as friend function b) as member function c) as non-friend, non-member function
JAVA -The next three questions use the following class: class Identification { private int idNum;   ...
JAVA -The next three questions use the following class: class Identification { private int idNum;    public Identification() { this(0); }    public Identification(int startingIdNum) { idNum = startingIdNum; }    public int getIdNum() { return idNum; }    public void setIdNum(int idNum) { this.idNum = idNum; } } Here is one program using the above class: public class Main {    public static void main(String[] args) {        Identification i1 = new Identification();        Identification i2 =...
1. Consider the following code: public class Widget implements Serializable { private int x; public void...
1. Consider the following code: public class Widget implements Serializable { private int x; public void setX( int d ) { x = d; } public int getX() { return x; } writeObject( Object o ) { o.writeInt(x); } } Which of the following statements is true? I. The Widget class is not serializable because no constructor is defined. II. The Widget class is not serializable because the implementation of writeObject() is not needed. III. The code will not compile...
public class ProductThread { static class ProductThreads extends Thread{ private int begin, end; int[] v1, v2;...
public class ProductThread { static class ProductThreads extends Thread{ private int begin, end; int[] v1, v2; long ris; public ProductThreads(String name, int [] v1, int [] v2, int begin, int end) { setName(name); this.v1 = v1; this.v2 = v2; this.begin = begin; this.end = end; this.ris = 0; } public void run() { System.out.println("Thread " + Thread.currentThread().getName() + "[" + begin + "," + end + "] started"); ris = 1; for(int i = begin; i <= end; i++) ris...
import javax.swing.JOptionPane; public class Animal {    private int numTeeth = 0;    private boolean spots...
import javax.swing.JOptionPane; public class Animal {    private int numTeeth = 0;    private boolean spots = false;    public int weight = 0;       public Animal(int numTeeth, boolean spots, int weight){        this.numTeeth =numTeeth;        this.spots = spots;        this.weight =weight;    }       public int getNumTeeth(){        return numTeeth;    }    public void setNumTeeth(int numTeeth) {        this.numTeeth = numTeeth;    }       public boolean getSpots() {       ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT