Undefined Behaviour
Undefined Behaviour

Reputation: 749

is it possible to assign base class's struct to dervied class's struct

I have class A which has struct as member and another class B which inherit class A and class B's struct inherit class A's struct.

class A
{
public:
    struct st
    {
        int x;
        int y;
    };
};

class B : public A
{
public:
    struct st : A::st
    {
        int z;
    };
};

following code give me error: what is the way to do this thing

B::st* obj = NULL; 

obj = new A::st [10]; 

Upvotes: 0

Views: 53

Answers (1)

R Sahu
R Sahu

Reputation: 206647

What you are trying is wrong since B::st is sub-type of A::st. Hence, a pointer to A::st cannot be automatically converted to a pointer of type B::st.

For the same reason, you can't use:

B* bPtr = new A;

You can do the other way around.

A::st* obj = NULL; 
obj = new B::st;  // Don't use the array new. That is going to be problematic. 

Upvotes: 2

Related Questions