I just want to find an answer to this question
Let A be a parent class with B,C the child classes.
Now we create objects as follows,
- A o1 = new A();
- B o2 = new B();
-
C o3 = new C();
-
A o4 = new B();
- B o5 = new A();
- C o6 = new B();
From these which will all create errors and why.. I got confused a lot because from 6 we know that it is an error because b may have some specialized variables and 7 is possible and 8 is not possible.
If i’m wrong please correct me and also,
- A o7 = o4;
- B 08 = o5;
Kindly suggest me the right answers and with explanations and also give me links for tutorials with this kind of puzzles.
Assuming all objects are of pointer types-
Explanation for 4 & 5:
new B()callsA'sconstructor followed byB'sconstructor. So, we have sub-objects of typeA*,B*. Since, there is a sub-object of typeA*, the lvalue can point to it which is also equal to of typeA*. This is helpful to access base class overridden virtual methods in derived class.new A()constructs an object of typeA*and returns it’s address. So, return type is ofA*but the receiving type is ofB*. So, they both are incompatible and is wrong.Example: Output results
};
};
Results:
Constructor A
Constructor A
Constructor B
Constructor A
Constructor C
Destructor A
Destructor B
Destructor A
Destructor C
Destructor A
Notice that the order of destruction is reverse to the order of construction.