Heyo, I have a question about this issue I am having in C++. I am new to C++ and learning. I have experience in object oriented programming so I am looking for the correct way and solve this issue and why it should be done that way.
Classes
I have separated each class into an interface header file and implementation cpp file.
The first class "Alpha" is my base class:
// a.h
#pragma once
class Alpha
{
public:
virtual void myFunction();
};
Alpha Implementation:
// a.cpp
#include <iostream>
#include "a.h"
void Alpha::myFunction()
{
std::cout << "Class Alpha myFunction" << std::endl;
}
I then have a sub class "Beta":
// b.h
#pragma once
#include "a.h"
#include "a.cpp"
class Beta : public Alpha
{
public:
virtual void myFunction();
};
Beta Implementation:
// b.cpp
#include <iostream>
#include "b.h"
void Beta::myFunction()
{
std::cout << "Class Beta myFunction" << std::endl;
}
I then have what will be like a manager class called "Gamma".
// g.h
#pragma once
#include <vector>
#include "a.h"
#include "a.cpp"
class Gamma
{
public:
void run();
std::vector<std::shared_ptr<Alpha>> alphaCollection;
};
Gamma implementation:
// g.cpp
#include "g.h"
#include "b.h"
#include "b.cpp"
void Gamma::run()
{
Beta localBeta;
alphaCollection.push_back(std::make_shared<Beta>(localBeta));
// example usage
alphaCollection.at(0)->myFunction();
}
Then finally my main:
#include "g.h";
#include "g.cpp";
int main()
{
Gamma objectG;
objectG.run();
}
Why I am doing this
The purpose for all of this being that I want a vector of the base class Alpha in my manager where I can then insert elements of a varying number of base class objects.
I used Beta as an example of a derived class but in the real implementation would have more derived classes such as Charlie, Delta etc.
The goal being that my Manager class Gamma will be able to operate on the vector elements as Alpha objects and each of the sub classes perform their own behavior.
The Problem
I cannot compile the above example because of how Gamma's implementation file includes "g.h" and "b.h" each of which include "a.h" and "a.cpp" thus double including "a.cpp" since it has no header guard.
- error C2084: function 'void Alpha::myFunction(void)' already has a body a.cpp
- error C2264: 'Alpha::myFunction' : error in function definition or declaration; function not called g.cpp
I have read varying opinions on how to use includes and overall I just feel like a noob in understanding the proper way to organize code to prevent his.
- Am I very disorganized?
- Should implementation files use header guards too?
- Should I be using forward declarations? If so how?
- Am I crazy to want the implementation to include the sub class includes while the header includes the base class include only?
Seriously any guidance is appreciated!