I have this doubt on base-derived class relationship.
i know when we derive an class from the base class, the derived class would have all the information about the base class. but the base class wouldnt know anything about the derived class.
so, why is this acceptable?
Base *b=new Derived();
and not
Derived *d=new Base();.
and basically i need to understand the need of the first statement? i mean, what is the use of assigning the derived class object to the base class pointer?
Note : This is not an assignment. im in the early stage of learning programming. so basically need to understands the bits and pieces. Please ignore if this is very basic and already asked question.
When the Derived
class object is made the Base
class constructor is called first. The Derived
class object contains the Base
class object. This allows it to call its Base
functions. Whereas a Base
class object does not contain a Derived
class object
Base *b=new Derived();
is useful in situations where you can use a single function to handle all derived class objects.
Consider,
Parent class : Animal Derived classes: Dog, Cat etc
Now, you have a function
void doSomethingtoTheAnimal(//take Animal here);
If you were not allowed to assign a base class object to parent reference variable. You will have to create a separate function for Dog
, Cat
and so on.
void doSomethingtoTheAnimal(Cat *b) or void doSomethingtoTheAnimal(Dog *b)
However, with polymorphism you can use void doSomethingtoTheAnimal(Base *b);
Then you can do
Base *b1 = new Dog()
or Base *b2 = new Cat();
and use the same function doSomethingtoTheAnimal(b1)
or doSomethingtoTheAnimal(b2)
Also, the base class pointer when pointing to a derived class object can only call either the functions in parent class or overriden ones in child class. It is not aware of functions defined exclusively in the child class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With