0

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.

5
  • 3
    Are you having any problems doing that? Commented May 17, 2022 at 13:26
  • You can initialize dummy data member in the constructor initializer list. Commented May 17, 2022 at 13:28
  • And how could i access the dummy then from inside the function some_func()? Commented May 17, 2022 at 13:29
  • Apart from inefficiency, your code is perfectly valid. The inefficiency comes from objects being copied unnecessarily. Commented May 17, 2022 at 13:31
  • 1
    @majomere You access it the way you do in the question. Are you having an actual problem or are you just assuming that this can't possibly be correct? Commented May 17, 2022 at 13:42

2 Answers 2

2

In your case Dummy has a default constructor, so you should have no problem 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?.
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments