Home > Mobile >  Initialize a class object inside a class object - C
Initialize a class object inside a class object - C

Time:05-18

How can i initialize a class object from within another class object.

class Dummy {
    public:
    Dummy() {}
};
class Server {
    public:
    string ip;
    string port;
    Dummy dummy; // <-- declare an object from within another object.
    public:
    Server(string port__, string ip__, Dummy dummy__) {
        port = port__;
        ip = ip__;
        dummy = dummy__;
    }
    void some_func() {
        // use dummy from here.
        dummy.hello_world();
    }
}

And what i want to do is use object Dummy throughout the object Server.

CodePudding user response:

In your case Dummy has a default constructor, so you should have no porblem doing it the way you did.

You can also use member initializer list, as you can see below:

Server(string ip__, string port__, Dummy dummy__)
   : ip(ip__), port(port__), dummy(dummy__) 
{}

This method will work even if Dummy does not have a default constructor.

Afterwards you can use the dummy member anywhere in class Server. At the moment you did not define any public member in class Dummy.
Once you do, you can use: dummy.<some_public_member_of_Dummy> throughout Server.

Side notes:

  1. It will be more efficient to pass arguments to the Server constructor by a const refernce, e.g.: Dummy const & dummy__.
  2. Better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

CodePudding user response:

You can initialize the data member dummy in the constructor initializer list of Server::Server(std::string, std::string, Dummy) as shown below:

class Server{
//other code here
    
Server(string port__, string ip__, Dummy dummy__)
//---------------------------vvvvvvvvvvvvvv----------->initialize dummy in constructor initializer list
    :port(port__), ip(ip__), dummy(dummy__) {
       
    }
};

Working demo

Note that your Dummy class has no member function named hello_world so you cannot call that function on Dummy object.

  •  Tags:  
  • c
  • Related