top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C++ : Why a constant object can call only constant member function ?

0 votes
754 views

How does compiler work internally to make sure constant object can access only constant member function ?

posted Apr 4, 2020 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Each member function holds internal this pointer which holds the address of the object which is calling the method.
If an object itself is a constant then this pointer should be "const this *" rather simple "this *". That is the reason when program call a non-constant method using a constant object, compiler throws compilation error.

answer Jan 29, 2021 by Vimal Kumar Mishra
Similar Questions
+1 vote

I have written a simple program and stored it with .c file,
When i compiled it with g++ it is getting compiled and giving the proper output when i run that,
but when i compile the same using gcc then it is throwing error.

Below is the sample .c file
#include<stdio.h>
struct A{
        private:
        int a;
        public:
        int sum(){
        a=10;
        }
        void print()
        {
        printf("%d\n",a);
        }
        A()
        {
                printf("Constructor\n");
        }
        A(int b)
        {
                printf("Copy Constructor\n");
        }
        ~A()
        {
                printf("Destructor\n");
        }
};
main()
{
        struct A a(10);
        a.sum();
        a.print();
}
...