Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling constructor of another class through Initialization list. Having problems

This is my sample code:

#include <iostream>
using namespace std;

class Base
{
public:
    Base (int v, char z) {x=v;y=z;};
    int x;
    char y;
};

class Bar
{
public:
    Bar(int m, char n):q(m),s(n),base(q,s){};
    Base base;
    int q;
    char s;    
};

int main()
{
    Bar barObj(5,'h');    
    cout << barObj.base.x << barObj.base.y << endl;       
    return 0;
}

Why am I getting an output of 0? http://ideone.com/pf47j

Also, in general, what is the right method to create a member object in another class and call the constructor of that object, as was done above with object base of class Base, inside class Bar?

like image 681
user1084113 Avatar asked Jul 20 '12 17:07

user1084113


People also ask

Does initializer list call constructor?

An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.

Should my constructors use initialization lists or assignment?

Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment.

What is the problem of initialization in constructor in C++?

Problem of initialization in C++ Therefore, when objects are created, the members of the object cannot be initialized directly and this problem of not being able to initialize data members is known as the problem of initialization.

What is initialization list in constructor?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.


1 Answers

The initialization order of data members follow their declaration order, not the order you list their initializer. Thus, Bar::base is always initialized before Bar::q and Bar::s.
As shown in http://ideone.com/M6iKR , for Bar::Bar(int m, char n), initialize base using m and n works fine.

like image 58
timrau Avatar answered Oct 21 '22 17:10

timrau