0

I am c beginer to c++ and i found something strange and was not able to understand couldn't find anything on internet so wanted to ask here. The code i saw was this:

#include<iostream>
using namespace std;

class A 
{
    protected : int a;
    public:
        A(int a) 
        {
            this -> a = a;
        }
    virtual void foo() 
    {
        cout<<"A =" <<a <<endl;
    }
};

class B: public A 
{
    public: B(int b): A(b + 1) {}
    virtual void foo() 
    {
        cout<<"B =" <<a <<endl;
    }
};

int main(int argc, char * * argv)
{
    A * a = new B(1);
    a -> foo();
    return 0;
}

the line that creates problem to me is this public: B(int b): A(b + 1) {}in derived class. Where i can obserrve that Derived class inheriting the base class constructor and its output is B=2. Could someone please explain me in detail how it became possible ? that in line A * a = new B(1); here "1" is passed as object and its value gets increased in A(b + 1) {} constructor by inheriting from A class in line public: B(int b): A(b + 1) {}.

Sss
  • 1,519
  • 8
  • 37
  • 67

2 Answers2

2

This is more detail then necessary, but here we go.

A * a = new B(1);

This line creates a new B object, passing 1 to its constructor.

class B: public A 
{
    public: B(int b): A(b + 1) {}

The constructor receives 1, then calls the A base constructor with b + 1 (2)

A(int a) 
{
  this -> a = a;
}

A's constructor sets a to 2.

Because you used the virtual keyword on foo(), you are saying: "Hey compiler, use dynamic binding for this function call." This means that if a is an A then A::foo will be called. If a is a B ("hiding" in its base type A) then the compiler will call B::foo.

A * a = new B(1);

The fact that a B object can live in an A object is the concept of "polymorphic objects". The fact that the virtual keyword tells the compiler to dispatch the function call to either A::foo or B::foo is the concept of "dynamic binding" or "functional polymorphism".

a -> foo();

Here we see dynamic binding in action. B::foo() is called which returns B = 2

  • thanks for the beauttiful answer. I couldnt understand tthis line, could you please explain it : "This means that if a is an A then A::foo will be called. If a is a B ("hiding" in its base type A) then the compiler will call B::foo" – Sss Jul 10 '14 at 23:11
  • and both of the functions are virtual. – Sss Jul 10 '14 at 23:13
1

This record

public: B(int b): A(b + 1) {}

does not mean the inheritance of the base constructor. it means that the base class constructor is called in the mem-initializer list of the derived class constructor.

For example you coudl rewrite constructor of class A

    A(int a) 
    {
        this -> a = a;
    }

the following way

    A(int a) : a( a ) 
    {
    }

It does not mean that class A inherites int a. it means that data member a is initialized by parameter a.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335