-1

If I have 2 classes, one with a custom constructor, and the other with an instance of the first class. How do I create that instance with the custom constructor.

For example:

a.h

class A
{
public:
    A(std::string input);
};

b.h

Class B
{
public:
    A a("Greetings");
};

This wouldn't work properly, it gives the error "expected a type specifier" on the string itself, and whenever I use a member of class A in class B, it says "expression must have a class type"

I'm assuming this means I'd need to make it

A a(std::string words);

But I'm not sure where or how I would define what the string should be.

  • 6
    `A a{"Greetings"};` will work. What you really need is one of [these](http://stackoverflow.com/q/388242/241631). – Praetorian Jul 07 '16 at 21:25

1 Answers1

2

Use the constructor's initialization list:

class A
{
public:
    A (std::string input);
};

class B
{
    A a;
public:
    B (std::string s) : a (s) {}; //This calls the constructor of A on 'a'
};

Also, in C++11 you can use the uniform initializer syntax:

class B
{
    A a {"Greetings"}.
    ...
};

But with this, you can only call the constructor with a compile-time constant.

Mattia F.
  • 1,720
  • 11
  • 21