Alright, so I'm trying to learn C++, and I've got two objects that are both subclasses("testgame") of a parent class("game"). Here are the definitions of both:
//game.h
#pragma once
#include <string>
class game
{
public:
virtual ~game() {
}
virtual std::string getTitle() = 0;
virtual bool setup() = 0;
virtual void start() = 0;
virtual void update() = 0;
};
And testgame
//testgame.h
#pragma once
#include "game.h"
#include <iostream>
class testgame :
public game
{
public:
std::string name;
testgame(std::string name) {
this->name = name;
}
~testgame() {
std::cout << name << " is being destroyed..." << std::endl;
delete this;
}
bool setup() {
std::cout << name << std::endl;
return true;
}
void start() {
std::cout << name << std::endl;
}
void update() {
std::cout << name << std::endl;
}
std::string getTitle() {
return name;
}
};
Now, when I try to do this:
#include "game.h"
#include "testgame.h"
...
game* game = new testgame("game1");
game* game2 = new testgame("game2");
...
game2 has an error saying that game2 is undefined. But, if I comment out game's declaration, the error goes away. Can someone help me figure out what exactly is going on here?
In general, naming variables the same as types will result in rather confusing parses.
game* game = new testgame("game1");
Now game is a value. So the second line parses as, believe it or not, multiplication.
(game * game2) = new testgame("game2");
which is understandably nonsense. Hence, game2 is a name that doesn't exist and we're trying to "multiply" by it. Simply name your variable game1 or anything that isn't a type and it will work out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With