Let's say we have a library that has a class "Car" which has some private members of class "Wheel".
We want the user to be able to create a "Car" and use the "Drive" function(ality) of it. This will also turn the wheels.
However, we want to avoid the user to create a "Wheel" by itself and turn it w/o the use of a car. To avoid them using the library improperly.
See example code below, where the main.cpp is the user code and the rest is the library.
main.cpp
#include <iostream>
#include "car.h"
int main()
{
std::cout << "Hello World" << std::endl;
Car myCar = Car();
myCar.drive();
//This should not be possible!
Wheel someWheel = Wheel();
someWheel.rotate();
return 0;
}
car.h
class Wheel;//Forward declaration (to avoid '#include "wheel.h"', which would make it accessible in main.cpp.
class Car {
public:
Car();
void drive();
private:
Wheel leftWheel;//Error, requires a pointer
};
car.cpp
#include <iostream>
#include "car.h"
#include "wheel.h"
Car::Car(){
leftWheel = new Wheel();
};
void Car::drive(){
std::cout << "Vroom!" << std::endl;
leftWheel.rotate();
}
wheel.h
class Wheel {
public:
Wheel();
void rotate();
};
wheel.cpp
#include <iostream>
#include "wheel.h"
Wheel::Wheel(){
};
void Wheel::rotate(){
std::cout << "Wheel: *Rotates*" << std::endl;
}
We've found that by including the header file in the Car.cpp, we can achieve this. However, when we make a forward declaration of 'Wheel', we can only use a pointer to Wheel as a private member from Car.
Otherwise it leads to:
car.h:12:11: error: field ‘leftWheel’ has incomplete type ‘Wheel’
So my questions are:
- Should we at all hide 'Wheel' from the user, for his own 'safety'? Or is there a stronger reason not to do it?
- If so, can we achieve this without the use of a pointer
- If not, do we have to explicitly make a deconstructor that deletes the instance from memory?
- If so, can we achieve this without the use of a pointer