inheritance - C++ proper way for solve this inheritence include issue "already has a body"? -
heyo, have question issue having in c++. new c++ , learning. have experience in object oriented programming looking correct way , solve issue , why should done way.
classes
i have separated each class interface header file , implementation cpp file.
the first class "alpha" 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 have 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 have 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 main:
#include "g.h"; #include "g.cpp"; int main() { gamma objectg; objectg.run(); } why doing this
the purpose of being want vector of base class alpha in manager can insert elements of varying number of base class objects.
i used beta example of derived class in real implementation have more derived classes such charlie, delta etc.
the goal being manager class gamma able operate on vector elements alpha objects , each of sub classes perform own behavior.
the problem
i cannot compile above example because of how gamma's implementation file includes "g.h" , "b.h" each of include "a.h" , "a.cpp" double including "a.cpp" since has no header guard.
- error c2084: function 'void alpha::myfunction(void)' has 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 use includes , overall feel noob in understanding proper way organize code prevent his.
- am disorganized?
- should implementation files use header guards too?
- should using forward declarations? if how?
- am crazy want implementation include sub class includes while header includes base class include only?
seriously guidance appreciated!
do not #include cpp files. it's not required , that's causing issue.
#pragma once same include guard - remember it's not portable - it's specific current compiler.
you should not have include guards in cpp files because shouldn't #include them.
Comments
Post a Comment