0

I was trying to understand virtual functions, and came across the following code.

class Base
{
  public:
            void Method1 ()  {  std::cout << "Base::Method1" << std::endl;  }
    virtual void Method2 ()  {  std::cout << "Base::Method2" << std::endl;  }
};

class Derived : public Base
{
  public:
    void Method1 ()  {  std::cout << "Derived::Method1" << std::endl;  }
    void Method2 ()  {  std::cout << "Derived::Method2" << std::endl;  }
};

Base* obj = new Derived ();
  //  Note - constructed as Derived, but pointer stored as Base*

obj->Method1 ();  //  Prints "Base::Method1"
obj->Method2 ();  //  Prints "Derived::Method2"

Towards the end, how is a Base class pointer being initialized with derived class Constructor?

Ranjan Srinivas
  • 347
  • 1
  • 3
  • 10
  • 2
    related: http://stackoverflow.com/questions/4937180/a-base-class-pointer-can-point-to-a-derived-class-object-why-is-the-vice-versa – NathanOliver Aug 02 '16 at 17:42

3 Answers3

3

C++ allows an implicit cast from a derived pointer type to a base pointer type. This is safe because the memory layout of the derived type is the same as the base up to the size of the base class.

You example has a potential bug though, since you have lost track of the real type of obj. When it comes time to delete it, you will call the wrong destructor. This can be remedied by make the destructor virtual.

nate
  • 1,771
  • 12
  • 17
0

Its being initialised with the result of the call to the constructor. Calling new Derived () creates a pointer to a new Derived object. and since class Derived derives publicly from class Base the new object pointed to is a base (at the same time as being a derived).

ROX
  • 1,256
  • 8
  • 18
0

For the expression …

obj->Method1 ();  //  Prints "Base::Method1"

… the compiler sees a pointer to an instance object of Base. It looks-up for a method called Method1. It finds it as a non-virtual method. So it binds it statically (aka at compile time) and produces code that "directly" calls Base::Method1.

For the expression …

obj->Method2 ();  

… the compiler sees a pointer to an instance object of Base. It looks-up for a method called Method2. It finds it as a virtual method. So it does not bind it statically (aka at compile time), but produces code for a runtime look-up on the real class of the instance object obj points to. At runtime there is a instance object of Derived. Therefore Derived::Method2 will be found and executed.

Let's summarize that with a quote of the great Alan Kay:

Actually I made up the term "object-oriented", and I can tell you I did not have C++ in mind.

Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50