Derived & base class question

Hi folks,

I wrote the following bit of code. Although it compiles, i'm not quite understanding what actually happens when i execute: Base MyBase = MyDerived;
How does it actually come to be that this line passes the value assigned to the base class of MyDerived into my new "MyBase" class?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Base
{
public:
    int x;
    Base(int setBase)
        : x(setBase)
    {}
};
 
class Derived : public Base
{
public:
    Derived (int SetDevBase)
        : Base(SetDevBase)
    {}
};
 
int main()
{
    Derived MyDerived(99);
    Base MyBase = MyDerived;
    cout << MyBase.x << endl;
 
}
Last edited on
When you assign Derived to Base, what's actually happening is that the derived class is being implicitly cast to the base class. i.e. you're losing all derived data and any called to an overridden method will be invoked on the base class.
Base MyBase = MyDerived;

What you're looking for is this:
Base* MyBase = &MyDerived;

MyBase is now a pointer to the class, meaning that method calls on overridden methods will be invoked on the derived class.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Base {
public:
    int x;
    Base(int setBase) : x(setBase) { cout << "Base constructor" << endl; }
    virtual ~Base() { cout << "Base destructor" << endl; }
    virtual void modifyX( int val ) {
        x += val;
        cout << "Base method" << endl;
    }
};

class Derived {
public:
    int y;
    Derived(int setDevBase) : Base(setDevBase), y(0) { cout << "Derived constructor" << endl; }
    ~Derived() { cout << "Derived destructor" << endl; }
    void modifyX( int val ) override {
        x -= val;
        y++;
        cout << "Derived method" << endl;
     }
};

int main() {
    Derived myDerived(99);
    Base* basePtr = &myDerived;

    basePtr->modifyX( 1 );    //If this was still done your way, x would now be 100.
    cout << basePtr->x << endl; //Outputs 98

    cout << myDerived.y << endl; //Outputs 1 
Thanks for taking the time to reply, i think i inderstand it a little better now!
Topic archived. No new replies allowed.