3

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
}
Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75

2 Answers2

7

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(){
    //....
}
//....
Vlad
  • 18,195
  • 4
  • 41
  • 71
4

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;}
Robert
  • 6,412
  • 3
  • 24
  • 26