简体   繁体   中英

How to pass an object as another class constructor's parameter?

i have 2 classes, one class which inherits it's parameters from an abstract class:

class Child : public Base {
public:
    Child(string s, int i, ) : Base(s, i){};
    ... // methods
};

and another which has two overloaded constructors, one uses normal parameters and another, gets the same parameters but from the first class' already existing object:

header file:

class Other {
private:
    string s;
    int i; 
    Child o;
public:
    Other(string str, int num);
    Other(Child ob);
};

cpp file:

Other :: Other(string str, int num) : s(str), i(num) {/* this is where the error happens*/};
Other :: Other(Child ob) : o(ob) {
};

but when i try to compile i get an error at the marked place "C2512 'Other': no appropriate default constructor available"

What could be the problem? i really need to to pass that object into the constructor

Here:

Other :: Other(string str, int num) : s(str), i(num)

you need to construct the child object:

Other :: Other(string str, int num) : s(str), i(num), o(str, num ) {}

You don't have Child::Child() . Since you don't list o in the initializer list in the error line, Child::Child() is getting called. This empty constructor is automatically added when there is no other constructor. Given that you have Child::Child(string s, int i) , compiler will not auto create Child::Child() .

This occurs because Other has a Child member, but you haven't given Child a default constructor (a constructor that takes no arguments). Since Child doesn't have a default constructor, the compiler has no idea how to create an instance of Child , so you have to tell it.

Other :: Other(string str, int num) : s(str), i(num), o(some_value_of_type_Child) {};

I'm just guessing here but I suspect the Other constructor taking a string and an integer is supposed to use those arguments to construct the Child object.

Then you should do something like this instead:

Other:: Other(string str, int num) : o(str, num) {}

And of course remove the s and i member variables from the Other class.

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