Which of the following statements is correct?a)Base class pointer cann...
Explanation:
In object-oriented programming, inheritance is a way to create a new class from an existing class. The new class is called a derived class or subclass, and the existing class is called a base class or superclass. The derived class inherits all the properties and methods of the base class, and can add new properties and methods of its own.
When working with inheritance, it is common to use pointers to refer to objects of the derived class or the base class. However, there are some rules that must be followed when using pointers and inheritance.
Pointer to Base Class:
A pointer to a base class can point to an object of the base class or any of its derived classes. This is because a derived class is a type of its base class, and can be treated as such. For example:
BaseClass* ptr = new BaseClass(); // pointer to base class
BaseClass* ptr2 = new DerivedClass(); // pointer to derived class
In the above code, ptr is a pointer to the base class, and ptr2 is a pointer to the derived class. Both pointers can be used to point to objects of the base class or the derived class.
Pointer to Derived Class:
A pointer to a derived class can only point to an object of the derived class, not the base class. This is because a derived class has additional properties and methods that are not present in its base class, and a pointer to the base class cannot access them. For example:
DerivedClass* ptr3 = new DerivedClass(); // pointer to derived class
DerivedClass* ptr4 = new BaseClass(); // error: cannot convert from base class to derived class
In the above code, ptr3 is a pointer to the derived class, and ptr4 is a pointer to the base class. However, ptr4 cannot be used to point to an object of the derived class, because it does not have access to the additional properties and methods of the derived class.
Conclusion:
Based on the above explanation, option 'B' is the correct answer. A derived class pointer cannot point to a base class because a derived class has additional properties and methods that are not present in its base class, and a pointer to the base class cannot access them.
Which of the following statements is correct?a)Base class pointer cann...
- C++ does not allow a derived class pointer to point a base class pointer whereas Base class can point to a derived class object.
- Both base class and derived class can have pointer objects.
Hence, the correct answer is Option B
To learn more about Pointers: