Abstraction of C++

What abstraction C++ gives??

Please see the danger of initializing an object with another of the same class

class A
{
int m,*p;
public:
A(){m=12;p=&m;}
inline void print(){std::cout<<m<<*p;}
inline void modify(){*p=34;}
};

int main()
{
A a,b;
b=a;
b.modify();
a.print();
b.print();
return 0;
}

when we called modify of b, a's m got modified instead of b's. if another object can change members in the private section the whole abstraction fails right?

please tell ur views.
I see indeed the danger in using the compiler-provided copy constructor and assignment operator in classes that hold pointers, yes. I don't know, however, your actual point. Can you please be more specific?
Ya indeed its a danger of def. copy constructor provided by the compiler.
closed account (S6k9GNh0)
If you run this, m is given a separate (since m is allocated per class) allocation therefor p in b shouldn't point to the same location as p in a. This is a poor example of saying C++ doesn't provide decent abstraction. You're statement of calling modify() with b changes a should be incorrect in this example.

Also, please note that there's probably always a work around to get into the private members of a class. You can also change const variables via a const cast. That doesn't mean you should. C++ isn't very restrictive with anything.

If you'd like more advice, please provide a more productive question.
Last edited on
computerquip, the example does demonstrate what the OP describes. The line b = a; calls for the assignment operator. Since none was explicitly written, the compiler-provided one is used. This one will assign the address of a.m to b.p because that's the value of a.p.
It cannot change the private members of another class, and it does not. It only changes what is in the memory the member points to.

Okay this is an issue, but C++ lets you fix it with custom copy constructors.
Topic archived. No new replies allowed.