0
class first{
    int fa,fb;

    public:
        first();
        first(int x,int y);
        void display();
};

first::first():fa(0),fb(0){
       }

first::first(int x,int y):fa(x),fb(y){
}

void first::display(){
    cout<<fa<<" "<<fb;
}

class second{
    first f;
    int sa,sb;

    public:
        second();
        second(int x,int y,int a,int b);
        void display();
};

second::second():sa(0),sb(0){
}

second::second(int x,int y,int a,int b):f(x,y),sa(a),sb(b){
}

void second::display(){
    cout<<"The Numbers are ";
    f.display();
    cout<<" "<<sa<<" "<<sb<<endl;
}

I apologize if this question has been asked already.

This a simple code to demonstrate the working of nested classes in c++. However, in the class second, the object f even though it has been defined before, I am able to call a constructor on it using the construtor of second class. How is it possible to call a constructor on an already defined instance of a class?

aschepler
  • 70,891
  • 9
  • 107
  • 161
Getsuga
  • 13
  • 4

2 Answers2

0

The object first f; is a member of second. That means every second contains a first. So in the process of creating a second, a first must be created. Your mem-initializer f(x,y) specifies exactly how to create f while creating the second object.

aschepler
  • 70,891
  • 9
  • 107
  • 161
0

You mix different concepts, when a variable defined in a function:

void foo()
{
    Foobar f; // f is defined and default initialized  here
    Foobar d { 123 }; // d is defined and initialized with 123
}

and declared as a field within a class or struct:

struct boo {
    Foobar f; // f is declared as member of type boo and how it will be
              // initialized will be known in boo's constructor
              // not here

    boo() {} // f is default constructed
    boo( int i ) : f { i } {} // f is initialized with i
};

to make things worse for you in c++11 you can pass parameters to field constructor in place:

struct boo {
    Foobar d { 123 };  // d would be initialized with 123 if otherwise is not set in boo's constructor

    boo( int i ) : d { i } {} // 123 is ignored and d is initialized with i
    boo() {} // d { 123 } is used
};

so still even if you pass parameters to field how field is initialized is defined in boo's constructor.

Slava
  • 43,454
  • 1
  • 47
  • 90