Trouble with the headers of various c++ class in separate files - c++

I have 5 files, a main file and two classes with its two headers files like that:
file main.cpp:
#include "parent.hpp"
#include <iostream>
int main (){
Parent parentInstance;
parentInstance.function();
return 0;
}
file parent.hpp:
class Parent {
public:
void function();
};
file parent.cpp:
#include "child1.hpp"
void Parent::function() {
Child1 Child1Instance;
Child1Instance.speak();
}
file child1.hpp:
#include "parent.hpp"
#include <iostream>
class Child1 : public Parent {
public:
void speak();
};
file child1.cpp:
#include "child1.hpp"
void Child1::speak () {
std::cout << "Hi, I'm child1" << '\n';
}
It compile and works without any problem, -although it may have been done with bad practices-. The problem rises when I try to add a new class with its own cpp and hpp files, called Child2 that its basically the same code than Child1, but I don't know how organize properly the headers for make this code works:
void Parent::function() {
Child1 Child1Instance;
Child2 Child2Instance;
Child1Instance.speak();
Child2Instance.speak();
}
and return me:
Hi, I'm child1
Hi, I'm child2

Some rules:
A header file always has include guards (or #pragma once).
Every .cpp includes its corresponding .hpp as its first (non-comment) line.
Only include into a .cpp what you explicitly use in that .cpp.
This should solve most of your problems.
Some explanations:
Without the guards, you can end up including the same file twice transitively, say you include a.h and b.h, but b.h already includes a.h... This causes some confusing redefinition errors.
You must include the header so that function definitions in the .cpp correspond to the declarations in the .hpp. Having it on the very first line is just good practice.
Including exactly what you use avoids confusing errors if you forgot an #include somewhere else.

I'm very grateful for the comments, all my knowledge is self-taught...now the problem is easily solved:
main.cpp has no change.
file parent.hpp:
#ifndef _PARENT_HPP_
#define _PARENT_HPP_
class Parent {
public:
void function();
};
#endif /* _PARENT_HPP_ */
file parent.cpp:
#include "parent.hpp"
#include "child1.hpp"
#include "child2.hpp"
void Parent::function() {
Child1 Child1Instance;
Child2 Child2Instance;
Child1Instance.speak();
Child2Instance.speak();
}
file child1.hpp and child2.hpp (change 1 to 2):
#include "parent.hpp"
#include <iostream>
class Child1 : public Parent {
public:
void speak();
};
file child1.cpp and child2.cpp (change 1 to 2):
#include "child1.hpp"
void Child1::speak () {
std::cout << "Hi, I'm child1" << '\n';
}
And the result:
Hi, I'm child1
Hi, I'm child2
It works. However, I'd like to hear if there's anything that could be improved or a mistake that could be corrected.

Related

Problem with includes, base class undefined C2504

This is my EngineIncludes.h file:
#include <stdafx.h>
//Engine Includes
namespace Engine
{
//Classes: 23
class BaseObject;
class Console;
class Engine;
class Node;
template <class T> class Transform;
}
#include "core/BaseObject.h"
#include "core/Console.h"
#include "core/Engine.h"
#include "math/Transform.h"
#include "scene/Node.h"
//Global Objects
extern Engine::Console* CONSOLE;
extern Engine::Engine* CORE_ENGINE;
In stdafx.h I have regular stuff like OpenGL, std::map, boost... and I'm building a precompiled header as standard.
This is the Node.h file:
#ifndef _NODE_H
#define _NODE_H
#include <stdafx.h>
#include <EngineIncludes.h>
namespace Engine
{
class Node : public BaseObject
{
public:
Node();
~Node();
void SetParent(Node* parent);
Node* GetParent();
void SetTransform(const Transform<double> &transform);
Transform<double> GetTransform();
Transform<double> GetDerivedTransform();
Transform<double> GetInheritedTransform();
void Update();
private:
Transform<float> transform;
Transform<float> derived;
Node* parent;
};
}
#endif _NODE_H
I get 3 errors here. One C2504 that Engine::BaseObject is not defined. And two C2079 that both Transform transform and Transform use undefined class. Now this is the BaseObject.h:
#ifndef _BASE_OBJECT_H
#define _BASE_OBJECT_H
#include "stdafx.h"
#include "EngineIncludes.h"
namespace Engine
{
class BaseObject
{
public:
BaseObject()
{
id = CORE_ENGINE->GenerateID();
}
~BaseObject()
{
}
long GetID()
{
return id;
}
private:
long id;
};
}
#endif _BASE_OBJECT_H
Now I specifically fully defined BaseObject inside header file with no luck. Still the same error. But if I comment out forward declarations in EngineIncludes.h, the compiler freaks out with
extern Engine::Console* CONSOLE;
It literally ignores all #includes for whatever reason. I've never had an issue like this before. And I tried everything. I even created EngineIncludes.cpp file. I moved the contents of EngineIncludes.h into stdafx.h with no luck. It somehow just ignores #includes. Even if I put #include "BaseObject.h" inside "Node.h" nothing changes. When it compiles Node it has both Transform which is a template class and BaseObject undefined, even though both objects are clearly defined before Node with forward declarations and #includes.
I'm using Visual Studio 2010, but never had an issue like this. I looked into my previous projects and all is written the same fashion and works without problem.

Swarmed with identifier errors

I've been programming a Monopoly game for a final project. So I thought I was on a roll, and that I had everything figured out with my psuedocode. But, it seems I forgot how to deal with includes properly, I know that is the issue since I was able to refine it to that point, but I'm not sure how to fix it.
In this super stripped down version of my code I have three .h files "Space.h" which is an abstract/virtual class which has to be inherited by a variety of different spaces that can appear on a typical Monopoly board: properties, jail, taxes, Chance, Community Chest, etc. The function that has to be inherited is run(Player&) which is what is "run" when you land on that particular space on the board, all functions that use run use a player passed by argument.
#pragma once
#include <string>
#include "Player.h"
class Space
{
public:
virtual void run(Player&) = 0;
};
My second .h file is the "Property.h" this inherits from Space
#pragma once
#include "Space.h"
class Property : Space
{
public:
void run(Player&) override;
int i{ 0 };
};
Lastly I have the "Player.h" which has two variables a name and a vector of properties it owns.
#pragma once
#include <string>
#include <vector>
#include "Property.h"
class Player
{
public:
std::string name{ "foo" };
void addProperty(Property p);
private:
std::vector <Property> ownedProperties;
};
Here's a very basic Property implementation
#include "Property.h"
#include <iostream>
void Property::run(Player & p)
{
std::cout << p.name;
}
Player implementation
#include "Player.h"
#include <iostream>
void Player::addProperty(Property p)
{
ownedProperties.push_back(p);
}
And finally main
#include "Player.h"
#include "Space.h"
#include "Property.h"
int main()
{
Player p{};
Property prop{};
prop.run(p);
system("pause");
}
Every time this is run I get a slew of errors, I'm sure it's got to do something with the circular include logic, with player including property, and property including space, which includes player. But, I don't see a workaround considering #include is needed to know how everything is defined isn't? Or are these errors referring to something else?
You have a circular include problem. Player includes Property which includes Space which includes Player again.
You can break the circle by not including Player.h in Space.h and only forward declare the class
#pragma once
class Player;
class Space
{
public:
virtual void run(Player&) = 0;
};

Methods in new cpp files? [duplicate]

I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.
Let me explain better if you wouldn't understand:
I have one file: main.cpp inside it I have main function.
I have the second file: second.cpp inside I have a function called second() I want to call this function called second() from my main function..
Any help?
You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.
other.h
void MyFunc();
main.cpp
#include "other.h"
int main() {
MyFunc();
}
other.cpp
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.
In second.h you just declare like this void yourFunction();
In second.cpp you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h" also in the beginning of second.cpp
Hope this helps:)
You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

C++: Inclusion inside inclusion

The title might not be very clear, it's a bit more complex than that. I searched the web for something like my problem but I did not find anything that could help me.
This is not about infinite looping inclusions, I already put preprocessor directives to avoid that.
I have two classes Monster and Character, respectively declared in their own header files, monster.hpp and character.hpp, and respectively implemented in their own source files, monster.cpp and character.cpp.
The problem now is that both classes need each other to work.
monster.hpp :
#ifndef INCLUDE_MONSTER_HPP
#define INCLUDE_MONSTER_HPP
#include "character.hpp"
class Monster
{
private: //Atributes
public: //Methods
void attackM(Monster& id);
void attackC(Character& id);
};
#endif //MONSTER_HPP_INCLUDED
character.hpp :
#ifndef INCLUDE_CHARACTER_HPP
#define INCLUDE_CHARACTER_HPP
#include "monster.hpp"
class Character
{
private: //Attributes
public: //Methods
void attackM(Monster& id);
void attackC(Character& id);
};
#endif //CHARACTER_HPP_INCLUDED
and the main.cpp :
#include <iostream>
#include "character.hpp"
#include "monster.hpp"
using namespace std;
int main(int argc, char **argv)
{
//Whatever
return 0;
}
And I get this error from the compiler :
In file included from character.hpp:7:0,
from main.cpp:3:
monster.hpp:24:16: error: 'Character' has not been declared
void attackC(Character& id);
(the line and column numbers may be wrong)
From what I understand, when monster.hpp is included into character.hpp, the compiler sees that the class Monster uses the class Character, which is not declared yet right at the moment when monster.hpp is included into character.hpp.
And I don't know how to fix that.
Any ideas ?
The way this works is that the header files of char and monster do not include each other. Instead you forward declare the classes and include the headers within the CPP files.
So basically replace #include "monster.hpp" in the.h with class Monster; and #include "monster.hpp" in the .cpp - and same for the other class.
See this question for more details:
What are forward declarations in C++?
#ifndef INCLUDE_MONSTER_HPP
#define INCLUDE_MONSTER_HPP
#include "character.hpp"
class Character;
class Monster
{
private: //Atributes
public: //Methods
void attackM(Monster& id);
void attackC(Character& id);
};
#endif //MONSTER_HPP_INCLUDED
You need to use a forward declaration. See: http://en.wikipedia.org/wiki/Forward_declaration
Basically, the compiler doesn't know what a "Character" is. You temporarily indicate that it's something you can point to by adding the following stub to Character.hpp:
class Character;
Use predeclaration in *.h:
class Character;
class Monster;
use in *cpp the includes:
#include "character.h"
#include "monster.h"
Or put everything in one *.hpp with predeclaration.

Using multiple .cpp files in c++ program?

I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.
Let me explain better if you wouldn't understand:
I have one file: main.cpp inside it I have main function.
I have the second file: second.cpp inside I have a function called second() I want to call this function called second() from my main function..
Any help?
You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.
other.h
void MyFunc();
main.cpp
#include "other.h"
int main() {
MyFunc();
}
other.cpp
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.
In second.h you just declare like this void yourFunction();
In second.cpp you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h" also in the beginning of second.cpp
Hope this helps:)
You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.