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

public class Clock { private int hr; private int min; private int sec; public Clock() {...
public class Clock { private int hr; private int min; private int sec; public Clock() { setTime(0, 0, 0); } public Clock(int hours, int minutes, int seconds) { setTime(hours, minutes, seconds); } public void setTime(int hours, int minutes, int seconds) { if (0 <= hours && hours < 24) hr = hours; else hr = 0; if (0 <= minutes && minutes < 60) min = minutes; else min = 0; if(0 <= seconds && seconds < 60) sec =...
#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...
Consider the following java class: class Student {    private int student_Number;    private String student_Name;    public Student(int...
Consider the following java class: class Student {    private int student_Number;    private String student_Name;    public Student(int stNo,String name) {         student_Number=stNo;         student_Name=name;      }     public String getName() {       return student_Name;     }      public int getNumber() {       return student_Number;      }     public void setName(String st_name) {       student_Name = st_name;     } } Write a Tester class named StudentTester which contains the following instruction: Use the contractor to create a student object where student_Number =12567, student_Name = “Ali”. Use the setName method to change the name of...
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...
For Questions 1-3: consider the following code: public class A { private int number; protected String...
For Questions 1-3: consider the following code: public class A { private int number; protected String name; public double price; public A() { System.out.println(“A() called”); } private void foo1() { System.out.println(“A version of foo1() called”); } protected int foo2() { Sysem.out.println(“A version of foo2() called); return number; } public String foo3() { System.out.println(“A version of foo3() called”); Return “Hi”; } }//end class A public class B extends A { private char service; public B() {    super();    System.out.println(“B() called”);...
public class IntNode               {            private int data;            pri
public class IntNode               {            private int data;            private IntNode link;            public IntNode(int data, IntNode link){.. }            public int     getData( )          {.. }            public IntNode getLink( )           {.. }            public void    setData(int data)     {.. }            public void    setLink(IntNode link) {.. }         } All questions are based on the above class, and the following declaration.   // Declare an empty, singly linked list with a head and a tail reference. // you need to make sure that head always points to...
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...
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m...
package applications; public class Matrix { private int[][] m; public Matrix(int x, int y) { m = new int[x][y]; } public Matrix(int x, int y, int z) { m = new int[x][y]; for(int i = 0; i < x; i++) { for(int j = 0; j < y; j++) { m[i][j] = z; } } } public int rowsum(int i) throws IndexOutOfBoundsException { if (i < 0 || i > m.length-1) { throw new IndexOutOfBoundsException("Invalid Row"); } int sum =...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT