Declaring an Object With No Default Constructor as a Member of Another Class

Suppose you have a class called A, which doesn’t have a default constructor, and you want to embed an instance of this class as a member of another class, B:

   class A  {  public:    A (int n);   // no default constructor  };

When you instantiate an ordinary object of class A, you pass an argument to its constructor like this:

   A a(3); // OK

However, you can’t do that when declaring an instance of A as a member of another class:

   class B  {  public:    B();  private:    A a(3); // error  };

You should use a member-initialization list in the containing class’s constructor to pass the embedded object’s argument:

   class B  {  public:    B() : a(3) {} // pass argument to embedded object  private:    A a; // no argument here  };

Some classes have both a default constructor and a constructor that takes one or more arguments, (e.g., std::vector). With such classes, you should use a member-initialization list to invoke a constructor that takes arguments:

   class Document  {  private:    vector  vc; // no argument here  public:    Document() : vc(80){} // similar to vector  vc (80)  };

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a