Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define class constructor inside another class header file?

This is a basic question but gives me hard time. I have class A and in the header file I want to define another class constructor B from another header file. I tried this code below which I'm sure that's not the correct way.

A.h

class A{
public:
    A();
    B b();  //Constructor from another Class that defined in another header file
    void Operation();
};

I need to call the constructor B in A.h so I can call the constructor B inside constructor A and also use function in Class B inside A::Operation().

A.cpp

#include "A.h"
#include "B.h"
A::A{
    b();  //call constructor b
}

void A::Operation(){
    b.someFunction();  //use function from class B, error here
}

As expected, the error I got is at b.someFunction()

expression must have class type

Anyone know how to define another class's constructor inside another class header file properly? And call the other constructor inside main class constructor and use the other class's function globally? Sorry for basic and confusing question.

like image 756
gameon67 Avatar asked Jun 03 '26 19:06

gameon67


1 Answers

This is not a constructor:

class A{
public:
    A();
    B b();  //This is a function named b, returning an object of type B
    void Operation();
};

Same here:

A::A{
    b();  //call function b from above, that returns a B object
}

And same here:

void A::Operation(){
    b.someFunction();  // Without invoking method b, you apply the dot operator on the method - which is illegal.
}

You probably want an object of type B, and call someFunction method on it. Maybe you want:

class A{
public:
    A();
    B b; // this is object named b, of type B
    void Operation();
};

And then, if the constructor of B requires parameters, you can:

A::A () : b(constructor parameters) {
}

If there is no need to pass parameters, you can just omit the construction of b, and the language will simply use the default constructor of B (without parameters).

A::A ()  {
}
like image 136
Michael Veksler Avatar answered Jun 06 '26 08:06

Michael Veksler