简体   繁体   中英

C++: Initialising an object of a parameterized class inside another class

I want to write a C++ program in which an object of a parameterized class A-'a' has to be initialized inside another class B. I should not/can not initialize like 'A a(parameter list);' of class A while declaring the object variable 'a' which is outside the constructor of class B. The necessary parameters to the object 'a' are gotten through the constructor of B. How to initialize 'a' inside B's constructor with the required parameters?

Class A{
public:
    A(string s)
    {cout<<s;}
};

class B{
private:
    A a;
public:
    B(string path){
        a(path);
    }
};

With the above code I am getting errors. How to initialize the object a(path) inside the class B?

The feature you are looking for is member initializer list . In your example it would be used like this:

class B{
    B(string path) : a(path) {
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM