Base Class Pointer derived Class Object in C++


This pointer of base class will be able to temper functions and variables of its own class and can still point to derived class object. A base class pointer can point to a derived class object we can only access base class membera using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.

The program demonstrates inheritance in object-oriented programming using C++. It defines a base class car with a single method start() that prints the message "Car Start". Then it defines a derived class BMW, which inherits from the car base class and adds a new method AdvanceGear() that prints the message "BMW Advance Gear".

In the main() function, an object b of class BMW is created. Then a pointer p of type car is created and assigned the address of b. Since BMW is derived from car, a pointer of type car can point to an object of type BMW.

Finally, the start() method of the car class is called using the p pointer. This demonstrates the concept of virtual functions in C++, where a function in the base class can be overridden by a function in the derived class.

Note that the commented-out lines in main() demonstrate an alternate way to call the methods directly on the object o of class BMW.

Source Code

//Base Class Pointer derived Class Object
#include<iostream>
using namespace std;
 
class car  //Base Class
{
public:
    void start()
    {
        cout<<"Car Start"<<endl;
    }
};
 
class BMW:public car  //Derived Class
{
public:
    void AdvanceGear()
    {
        cout<<"BMW Advance Gear"<<endl;
    }
};
 
int main()
{
    /*BMW o;
    o.start();
    o.AdvanceGear();*/
    BMW b;
    car *p=NULL;
    p=&b;
    p->start();
    return 0;
}
 

Output

Car Start
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples