Self-test 2:
C++ const-ness

  1. Which is const class member function?

    class A
    {
      private:
        const int a(int); // [A]
        int b(const int); // [B]
        int c(int) const; // [C]
        ......
    };
    
    Solution
    C

  2. Which of the following definitions of a does not allow later assignment like below:

                       *a = 3;
    
    (There can be multiple answers.)
        int b = 100;
        const int* a = &b;           // [1]
        int const* a = &b;           // [2]
        int* const a = &b;           // [3]
        const int* const a = &b;     // [4]
    
    Solution
    [1][2][4]

  3. Which of the following definitions of pointer a does not allow later its re-direction to point to another object? (There can be multiple answers.)

        int b = 100;
        const int* a = &b;           // [1]
        int const* a = &b;           // [2]
        int* const a = &b;           // [3]
        const int* const a = &b;     // [4]
    
    Solution

    [3] [4]


  4. When a function is declared as "const char* GetString(void);" which of the following statements will compile with no warnings nor errors?

    1. char* str = GetString( );
    2. const char* str = GetString( );
    3. char* const str = GetString( );
    4. const char* const str = GetString( );
    Solution

    B,D


  5. What is the difference between the following two declarations of the function GetInt? Or are they are same in effect?

        const int GetInt(void)
        int GetInt(void)
    
    Solution

    Their effects are the same since the value returned is an copied value, so it doesn't really matter if it is a const or not.


  6. Which expression(s) below is(are) legal?

    1. const A_class* c = new A_class(); A_class* e = c;
    2. A_class* const c = new A_class(); A_class* b = c;
    Solution

    B


  7. Is the following, point out the illegal statements.

        class Stack
        {
          public:
    	void push(int elem);
    	int pop(void);
    	int getCount(void) const;
          private:
    	int num;
    	int data[100];
        };
    
        int Stack::getCount(void) const
        {
    	++num;   // [1]
    	pop();   // [2]
    	return num;
        }
    
    Solution

    [1][2]