Object and Constructor

Hello everyone. I'm new to the forum. I have experience in programming in C# and Java, while I don't know how to use C++.
I would like to do something like this... pass an object of type class1 to the constructor of the second object (like class2) as required by the constructor of class2.
How can I do it??? The compiler won't let me do it...
P.s. I know there's something missing in the syntax, but I'm on my phone and I don't feel like writing everything... Can anyone help me?
Below are what I would like to do...

This is in a file.cpp and then the declarations in file.h

class class1
{
private:
byte var1;
public:
class1 (byte lvar1) {
var1=lvar1;
};
};

class class2
{
private:
class1 varClass1;
public:
class2 (class1 lvarClass1) {
varClass1=lvarClass1;
};
};

Questo sul file.ino
...voglio creare un oggetto così:

class1 oggClasse1(10);
class2 oggClasse2(oggClasse);

I know some #include is missing... but that's not what's blocking me. Thanks in advance!!

Paolo

You should use a member initializer list:

class Class2 {
  private:
    Class1 varClass1;
  public:
    Class2(Class1 varClass1) : varClass1{varClass1} {}
};

Thanks very much. I will try it.
Bye

did you just need class1 () { }

typedef unsigned char byte;

class class1
{
  private:
    byte var1;
  public:
    class1 () { }
};

class class2
{
  private:
    class1 varClass1;
  public:
    class2 (
        class1 lvarClass1 )
    {
        varClass1 = lvarClass1;
    };
};

OP's use case in Post #1 required the class1 constructor to take an argument:
class1 oggClasse1(10);
So such an constructor must be provided.

That's an assignment statement, not an initialization. Probably doesn't make a difference for this trivial example, but it's a vital distinction with more complex classes. OP's use case in Post #1 required a copy constructor:
class2 oggClasse2(oggClasse1);
Also, Initialization of member classes must be done in the constructor's initialization list. So:

class class1 {
  private:
    uint8_t var1;
  public:
    class1(uint8_t x) : var1(x) {}
};

class class2 {
  private:
    class1 varClass1;
  public:
    class2 (const class1 &lvarClass1 ) : varClass1(lvarClass1) {}
};

class1 oggClasse1(10);
class2 oggClasse2(oggClasse1);

void setup() {
}

void loop() {
}

with this change, the code compiled. the error seemed to be because of definition that didn't need an initial value

PieterP, thanks very much. It worked perfectly.
Bye

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