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.
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 () {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With