PDA

View Full Version : declaring subclasses in C++



Paat
23rd October 2009, 01:41
hello, i'm trying to create subclasses to a class, but i get the same error to all my subclasses: expected class-name before*'{' token. Ive checked on other threads and site since it seems that this problem is very common. here is my code:

MoyenDeTransport.h:


class MoyenDeTransport
{
double litre;
public:
MoyenDeTransport(double);
double getLitre();
//void parcourir(int distance);

};


and here is my subclass:
Camion



class Camion: public MoyenDeTransport
{
public:
Camion();
};


as a matter of fact, i get one warning and one error:

warning: In File included from camion.cpp:1,
error: expected class-name before*'{' token

here is my camion.cpp:


#include "camion.h"

Camion::Camion()
{
}


and just in case, here is my MoyenDeTransport.cpp:



#include "moyendetransport.h"

MoyenDeTransport::MoyenDeTransport(double ammount)
{
litre = ammount;
}



I dont think i'm doing anything flagrantly wrong, but i'm sure its one small thing that i'm missing...

What do you guys think?

Paat

john_god
23rd October 2009, 01:56
I think you need to put a


#include "MoyenDeTransport.h"

in your moyen.h to let the derived class know here the base class is

Paat
23rd October 2009, 02:06
i tried that and i get an infinite amount of errors, because by adding that line of code, you're refering moyen.cpp to moyen.h, which is linked to moyen.cpp, which includes moyen.h, which is linked to moyen.cpp, which.... its an infinite loop.

squidge
23rd October 2009, 08:11
why would a header file include moyen.cpp?

Your camion class inherits MoyenDeTransport class, so Camion.h needs #include of MoyenDeTransport.h. Theres no need for MoyenDeTransport.h to include camion.h or any cpp files.

Also, you should really guard your header files from multiple inclusion. It makes things a lot easier later on when multiple objects depend on the same base classes.

scascio
23rd October 2009, 08:40
If your include directives leads to mutliple inclusions to the same file,
you need to prevent from mutliple class definition with #ifndef ID with a unique id you define yourself

So insert in your MoyenDeTransport.h :

#ifndef MOYENDETRANSPORT_H
#define MOYENDETRANSPORT_H

//definition of clas MoyenDeTransport

#endif
and in your Camion.h :

#ifndef CAMION_H // or any unique id you define yourself
#define CAMION_H

//defintion of class Camion

#endif