I tried making a simple DI test, where a class car is injected with a container interface.
It gives an error 'incomplete type', see the comment in the code.
What am I doing wrong?
#include <iostream>
#include <string>
class Car;
class IContainer {
public:
virtual ~IContainer()=default;
};
class Container: public IContainer {
public:
explicit Container(int i = 1) {
std::cout << std::to_string(i);
};
void makeCar() {
Car car(this); //Variable has incomplete type 'Car'
}
};
class Car {
public:
explicit Car(IContainer &container): c(container) {
printf("constructed\n");
}
private:
IContainer &c;
};
int main() {
Container container(5);
container.makeCar();
return 0;
}
Solution - here's the working modified code:
#include <iostream>
#include <string>
class Car;
class IContainer {
public:
virtual ~IContainer()=default;
virtual void foo(){}
};
class Container: public IContainer {
public:
explicit Container(int i = 1) {
std::cout << std::to_string(i) << std::endl;
};
void foo() override {
std::cout << "bar\n";
}
void makeCar();
};
class Car {
public:
explicit Car(IContainer *container): c(container) {
printf("Car constructed\n");
c->foo();
}
private:
IContainer *c;
};
void Container::makeCar() {
//Constructing the car will call a function on the injected container
Car car(this);
}
int main() {
Container container(5);
container.makeCar();
return 0;
}
Carbefore it has a complete declaration. PutContainer::makeCarafterCardeclaration.Containerclass, but to move the body ofmakeCarout of the class. You'll need a function prototype/declaration in the class, with no body. And a definition after all classes are defined.Carcode doesn't need theContainercode. It only needs theIContainercode: wandbox.org/permlink/HGX5w4e0QN94morn