Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this C++ identifier undefined?

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?

like image 659
Chall Avatar asked Jan 19 '26 15:01

Chall


1 Answers

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.

like image 153
Silvio Mayolo Avatar answered Jan 22 '26 05:01

Silvio Mayolo