Input class object into constructor of another class

I am trying to create a class object which has another custom class object as an input in the constructor.

My Code is:

class class1 {

  public:

    String str1;

    class1(String str) {

      str1 = str;

    }

};



class class2 {

  public:

    class1 class1var;



    class2(class1 someClass1Object) {

      class1var = someClass1Object;

    };

};

The error I am getting is :

error: no matching function for call to 'class1::class1()

What am I doing wrong?
Thanks

    class1 class1var;

In class2 you are trying to create an object of type class1 but you aren't passing the required String to the constructor. Maybe this will work to pass an empty string to the constructor.

    class1 class1var(String(""));

If your class includes a data member whose constructor takes arguments, then you must use an initializer list. See case #3 here: When do we use Initializer List in C++? - GeeksforGeeks

class1::class1() refers to the default constructor of class1, the constructor that takes no arguments. Your class1 does not have one, and the C++ spec does not give you one for free. If you want to be able to create class objects with no argument, you have to specify a default constructor.

    class2(class1 someClass1Object) {

      class1var = someClass1Object;

    };

The way you have coded this constructor, all of the class members will be initialized first (with default constructors), then the code in the {} braces will run and overwrite the initialization. And that doesn't work because class1 does not have a default constructor.

That doesn't mean you need to make one though. Because you're copying the object, the C++ spec does give you a free copy constructor on all classes you make. So you can use the initializer list feature gfvalvo linked to to do this. Specifically, it will look like this:

class class1 {
  public:
    String str1;
    class1(String str) {
      str1 = str;
    }
};

class class2 {
  public:
    class1 class1var;
    class2(class1 someClass1Object) : class1var(someClass1Object) {
    };
}; 


void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}

Thank you all,

Jiggy-Ninja's solution worked flawlessly. I was having some trouble with the syntax after reading the initialiser list notes but this has cleared things up.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.