Way around "first defined here" error? - c++

I need to have two alternate classes with the same name, that I can switch between each other by simply changing which class is included in main.
For example;
Mode_1.h
class Draw{
private:
// private stuff
public:
void Render(int x, char y);
};
Mode_2.h
class Draw{
private:
// private stuff
public:
void Render(int x, char y);
};
main.cpp
#include "Mode_1.h"
int main(){
Draw D;
int x = 2;
char y = 'x';
D.Render(x, y);
}
Currently I'm having to comment out the .h and .cpp files I'm not using to avoid the "first defined here" error. What I want is that all I have to do to switch between them is change
#include "Mode_1.h"
to
#include "Mode_2.h"

You should put them in different namespaces:
namespace Mode2
{
class Draw{
private:
// private stuff
public:
Draw(int x, char y);
};
}
In main you can then select the namespace you want to use:
#include "Mode_1.h"
#include "Mode_2.h"
using namespace Mode2;
int main()
{
Draw D;
int x = 2;
char y = 'x';
D.Draw(x, y);
return 0;
}

You may try like this:
#ifdef MODE1
#include "Mode_1.h"
#else
#include "Mode_2.h"
#endif
int main(){
Draw D;
int x = 2;
char y = 'x';
Draw(x, y);
}
And compile this source file with -DMODE1 or none depending on you wish to include Mode_1.h or Mode_2.h

Related

Trying to access variables from another class

Im having an issue getting my variable from my original class to print in another class method
Quick example of my issue:
say the variable was declared here in the test.h file:
class player{
private:
int x = 10;
void setX(); //method for setting X from user input
int getX(); //Method for retrieving variable
}
Then in another class method where i want to print X
class inTheWoods{
public:
printInfo();
}
test.cpp file:
void player::setX(){
cout << "Set X to a number:" << endl;
cin >> x
}
int player::getX(){
return x;
}
int inTheWoods::printInfo(){
player playerObj; //Player object to access methods in player class
cout << playerObj.getX();
}
main.cpp:
int main(){
inTheWoods woodsObj;
woodsObj.printInfo();
return 0;
}
Whenever I run my program that resembles this problem the int does not display correctly and throws me a strange negative number. I hope this isnt too much code and that I documented everything correctly
If you want the classes to be in a separate files, it should still work:
Main.cpp
#include <iostream>
#include "inTheWoods.h"
int main()
{
inTheWoods woodsObj;
woodsObj.printInfo();
return 0;
}
Player.h
#pragma once
#include <iostream>
class Player
{
int x = 10;
void setX();
public:
int getX();
};
Player.cpp
#include "Player.h"
void Player::setX()
{
std::cout << "Set X to a number:" << std::endl;
std::cin >> x;
}
int Player::getX()
{
return x;
}
inTheWoods.h
//#pragma once
#include "Player.h"
#include <iostream>
class inTheWoods
{
public:
void printInfo();
};
inTheWoods.cpp
#include "inTheWoods.h"
void inTheWoods::printInfo()
{
Player playerObj; //Player object to access methods in player class
std::cout << playerObj.getX();
}
#pragma once is a preprocessor that prevents multiple includes, in case you didn't know. You can choose to skip it (Visual Studio auto-generated the file with the line).
In summary, these are the changes I needed to make from your implementation:
Move declaration of getX() from private to public.
Add semicolons to the end of every class.
Add a return type to printInfo(). If you don't want a function to return anything, the return type is void. Unless you care declaring a constructor, which doesn't seem to be the case here.
Here is the working one. It's always a good practice to give a constructor, in order to create an instance with some default values. the following code will work hopefully according to your requirements:
main.cpp
#include <iostream>
#include "inTheWoods.h"
int main()
{
inTheWoods woodsObj;
woodsObj.printInfo();
return 0;
}
player.h
#pragma once
class player
{
private:
int m_x;
public:
player();
player(const int& x);
void setX(); //method for setting X from user input
const int& getX()const; //Method for retrieving variable
};
player.cpp
#include "player.h"
#include <iostream>
player::player() // defualt constructor
:m_x(0) {}
player::player(const int& x)
:m_x(x) {} // parameterised
void player::setX()
{
std::cout << "Set X to a number:" << std::endl;
std::cin >> m_x;
}
const int& player::getX()const
{
return m_x;
}
inTheWoods.h
#pragma once
class inTheWoods
{
public:
inTheWoods();
~inTheWoods();
void printInfo();
};
inTheWoods.cpp
#include "inTheWoods.h"
#include "player.h"
#include <iostream>
inTheWoods::inTheWoods() {}
inTheWoods::~inTheWoods() {}
void inTheWoods::printInfo()
{
//Player object to access methods in player class
player playerObj; // will beinitialized with 0
player playerObj2(10); // will beinitialized with 10
std::cout << playerObj.getX() <<std::endl;
std::cout << playerObj2.getX() <<std::endl;
}
Edit: Well if you wanna allow the user to set values your printInfo() must be as follows:
void inTheWoods::printInfo()
{
//Player object to access methods in player class
player playerObj; // will beinitialized with 0
playerObj.setX();
std::cout << playerObj.getX() <<std::endl;
}

How to use header functions in source file in C++?

I'm new to C++ programming language and it is different from Java. I tried to use functions from a header I made but when I use a function from the header , Eclipse C++ IDE says that member declaration is not found except for the constructor while it is found in the header as public.
Car.h file (header) :
#include <string>
using namespace std;
class Car {
private :
string name;
string model;
int year;
int width;
int height;
int depth;
public :
Car ();
Car (string n, string m, int y, int w, int h, int d);
void setName(string n);
void setModel (string m);
void setYear (int y);
void setSize (int w, int h, int d);
string getName ();
string getModel();
int getYear();
int getWidth();
int getHeight();
int getDepth();
};
Car.cpp file (source)
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car(string n, string m, int y, int w, int h, int d) { //works properly
name = n;
model = m;
year = y;
width = w;
height = h;
depth = d;
}
Car::getName() { // IDE says member declaration not found
return name;
}
Car::getModel() { // IDE says member declaration not found
return model;
}
Car::getYear() { // IDE says member declaration not found
return year;
}
Car::getWidth() { // IDE says member declaration not found
return width;
}
Car::getHeight () { // IDE says member declaration not found
return height;
}
What I have did wrong ?
All of your functions are missing the return type, for example
string Car::getName() {
return name;
}
The reason why Car works is because it is a Constructor and does not need a type declaration.
All the rest of your functions do.
int Car::getYear() { // IDE says member declaration not found
return year;
}
Do this :-
#include <iostream>
#include <string>
#include "Car.h"
using namespace std;
Car::Car(string n, string m, int y, int w, int h, int d) { //works properly
name = n;
model = m;
year = y;
width = w;
height = h;
depth = d;
}
string Car::getName() { // IDE says member declaration not found
return name;
}
string Car::getModel() { // IDE says member declaration not found
return model;
}
int Car::getYear() { // IDE says member declaration not found
return year;
}
int Car::getWidth() { // IDE says member declaration not found
return width;
}
int Car::getHeight () { // IDE says member declaration not found
return height;
}

Issue with forward declaring class

So I am trying to forward declare a class in my C++ project and then create it in main.
So I have player_obj.cpp which contains the class, classes.h which forward declares the class, and main.cpp which uses it.
classes.h
#ifndef CLASSES_H
#define CLASSES_H
class player_class
{
public:
int x;
int y;
char sprite;
int xprevious;
int yprevious;
private:
bool active;
public:
void update_xy();
player_class(int _x, int _y, char _sprite);
void step();
void destroy();
};
#endif
main.cpp
#include <iostream>
#include "classes.h"
using namespace std;
int main()
{
player_class player_obj (5,5,'#');
cout << player_obj.x << ", " << player_obj.y << endl;
return 0;
}
and player_obj.cpp
#include <iostream>
#include <Windows.h>
using namespace std;
class player_class
{
public:
//Coordinates
int x;
int y;
//Sprite
char sprite;
//Previous coordinates
int xprevious;
int yprevious;
//Not everyone can set the activity
private:
//Active
bool active;
//Update xprevious and yprevious - Called by the step event
void update_xy()
{
xprevious = x;
yprevious = y;
}
//All functions public
public:
//Create event/Constructer
player_class(int _x, int _y, char _sprite)
{
//Set default variables
x = _x;
y = _y;
sprite = _sprite;
xprevious = x;
yprevious = y;
active = true;
}
//Step event
void step()
{
//Update old xprevious and yprevious
update_xy();
//Do other stuff here
}
//Drestroy event
void destroy()
{
active = false;
}
};
I thought that would work out all right but when I compile and run it I get:
main.cpp:(.text+0x2c): undefined reference to`player_class::player_class(int, int, char)'
I've done some research, but I can't seem to fix this issue.
I greatly appreciate any help!
Well you're sort of close, what you have in your header is indeed a class declaration (not a forward declaration mind you).
The problem is you never defined it. What you have in player_obj.cpp is an abomination of class redefinition, but you already have your class declared. Just include the header file and define the functions one by one and you're done!
#include "classes.h"
player_class::player_class(int _x, int _y, char _sprite)
{
//Set default variables
x = _x;
y = _y;
sprite = _sprite;
xprevious = x;
yprevious = y;
active = true;
}
// and so on
If you're serious about learning modern C++ though, a few notes:
#pragma once is the modern way of guarding header files. Don't use those #ifdef..#endif constructs.
generally speaking, don't name anything starting with underscores. Especially not parameters visible as part of your public contract.
you have class initializers for a reason, use them! You don't need half a screen of copy pasting variables in your constructors.
You dont want a forward declaration. You want a declaration. It is a classical case of declaring a class in a header file and defining its functions in a cpp file. Then including the header where-ever you want to use your class
You only need forward declarations when you want to use a pointer to that class as a parameter to a function or a member variable somewhere but the definition of that class is not available yet.
Note that when you forward declare a class, you cannot use this class's member variables or functions in that header
-regards
Gautam

C++ inherited functions not being found

I new in C++ and I have difficulty to understand how to get my function with inheritance.
I have a Class that is link to another with inheritance, everything work except:
I cannot reach my superclass function.
Here's my class header : Point.h (I don't include the .cpp):
#ifndef Point_H
#define Point_H
#include <iostream>
class Point{
public:
Point();
void set_values (int , int);
void set_values (int , int , int );
void affichervaleurs();
int getX() const { return x; }
int getY() const { return y; }
private:
int x ;
int y ;
int z ;
};
#endif
Now My other class that try to access the function getX from Point.h :
The header : Carre.h
#ifndef Carre_H
#define Carre_H
#include "Point.h"
class Carre : public Point{
public:
Carre();
//Carre(int a , int b);
//Carre(int a, int b):Point(a,b) {};
//Carre(int a, int b, int c):Point(a, b, c) {};
//const Point &pp;
int Aire (){
};
void affichercar(){
};
};
#endif
Carre.cpp
#include <iostream>
using namespace std;
#include "Carre.h"
#include "Point.h"
Carre::Carre():Point(){
};
//Carre::Carre(int a, int b);
//const &pp;
int Aire (){
return (getX() * getY());
};
void affichercar(){
//cout << "Coordonnees X:" << x << endl;
};
It says that my GetX() is undeclared in my Carre.cpp .
Like I said I'm new in C++
Does someone know what I'm missing to make that code work. ?
Your definition is missing the class scope, which makes it a free function instead of a member.
It should be
int Carre::Aire (){
return getX() * getY();
};
In the .cpp file for Carre, the functions Aire and affichercar are global. Presumably you intended:
int Carre::Aire(){
return (getX() * getY());
};
For example.
Declaring function outside class body requires a class specifier:
int Carre::Aire () {
return (getX() * getY());
};
void Carre::affichercar() {
//...
}
Otherwise
int Aire () {
return (getX() * getY());
};
is just another function in global namespace that can exists simutaneously to Carre::Aire().
This is because you are not implementing the Aire function as being part of the Carre class.
Try changing
int Aire (){
to
int Carre::Aire (){
Also, you already have an implementation of the Aire method in the header file. You should either implement the function inline in the header file, or in the .cpp file, but not both. This also applies to your affichercar method.

Cannot access members of a class

I have a little problem, i probably included the class files wrongly, since i can't acces members of the enemy class. What am i doing wrong?
my cpp for class
#include "classes.h"
class Enemy
{
bool alive;
double posX,posY;
int enemyNum;
int animframe;
public:
Enemy(int col,int row)
{
animframe = rand() % 2;
posX = col*50;
posY = row*50;
}
Enemy()
{
}
void destroy()
{
alive = 0;
}
void setposX(double x)
{x = posX;}
void setposY(double y)
{y = posY;}
};
my header for class:
class Enemy;
my main:
#include "classes.h"
Enemy alien;
int main()
{
alien. // this is where intelisense tells me there are no members
}
Your main file will only see what you wrote in the header, which is that Enemy is a class. Normally, you'd declare your whole class with fields and method signatures in the header files, and provide implementations in the .cpp file.
classes.h:
#ifndef _CLASSES_H_
#define _CLASSES_H_
class Enemy
{
bool alive;
double posX,posY;
int enemyNum;
int animframe;
public:
Enemy(int col,int row);
Enemy();
void destroy();
void setposX(double x);
void setposY(double y);
};
#endif
classes.cpp:
#include "classes.h"
//....
void Enemy::destroy(){
//....
}
//....
In addition to Vlad's answer, your file with main doesn't know anything about the Enemy class, other than that it exists.
In general, the class declarations goes in the header file, and the function definitions go in another.
Consider splitting the files like:
classes.h:
#ifndef CLASSES_H
#define CLASSES_H
class Enemy
{
private:
bool alive;
double posX,posY;
int enemyNum;
int animframe;
public:
Enemy(int col,int row);
Enemy();
void destroy();
void setposX(double x);
void setposY(double y);
};
#endif//CLASSES_H
Note the "include guards" which prevent the same file from being included more than once. Good practice to use on header files, or else you get annoying compilation errors.
classes.cpp:
#include "classes.h"
Enemy::Enemy(int col,int row)
{
animframe = rand() % 2;
posX = col*50;
posY = row*50;
}
Enemy::Enemy()
{
}
void Enemy::destroy()
{
alive = 0;
}
void Enemy::setposX(double x) {x = posX;}
void Enemy::setposY(double y) {y = posY;}