-
Inheritance question
I'm a newbie to C++ and I'm getting an error I can't quite figure out....
Error
C:\development\C++\OOTesting\src\logic.cpp(20) : error C2509: 'get_floors' : member function not declared in 'House'
c:\development\c++\ootesting\src\logic.h(16) : see declaration of 'House'
C:\development\C++\OOTesting\src\logic.cpp(21) : error C2509: 'get_rooms' : member function not declared in 'House'
c:\development\c++\ootesting\src\logic.h(16) : see declaration of 'House'
logic.cpp
Code:
#include <iostream>
#include "logic.h"
using namespace std;
/* building functions */
Building::Building()
{
cout << "New building object created.\n";
}
/* house functions */
House::House()
{
cout << "New house object created\n";
}
House::get_baths() { return baths; }
House::get_bedrooms() { return bedrooms; }
House::get_floors() { return floors; }
House::get_rooms() { return rooms; }
logic.h
Code:
#include <iostream>
using namespace std;
class Building
{
int rooms, floors;
public:
Building();
void set_rooms(int num);
int get_rooms();
void set_floors(int num);
int get_floors();
};
class House : public Building
{
int bedrooms, baths;
public:
House();
void set_bedrooms(int num);
int get_bedrooms();
void set_baths(int num);
int get_baths();
};
main.cpp
Code:
#include <iostream>
#include "logic.h"
using namespace std;
void main()
{
House h;
}
-
Im sure you have worked it out by now..... be more careful.... match up function decs with function defs and you will spot your error (even tho the compiler tells you exactly what it is).
-
Well I know those functions are not declared in House, but I thought that since I'm inheriting from Building I would have access to them. :confused:
-
Oh crap, I'm an idiot. I just realized I'm providing the behavior of the function and not actually using it in main or something. Whoa... :(
-
You do.
but thats not what your doing.
In the header files you define an interface.
In the cpp files goes your implementation.
You have getrooms in building not house so to find the impl the compiler is looking for Building::getrooms() and not House::getrooms().
-
Code:
House::get_rooms() { return rooms; }
That line defines a function in the class House called get_rooms(). However, you did not declare a function in House called get_rooms(), and that is what the compiler is trying to tell you.
For both House and Building you should have their respective functions declared and defined, and inheritance does not affect that basic requirement for all classes(except for pure virtual functions).
So, the function above is really in the Building class, and it has another error because when you define a function you have to include the return type in the definition. It should look like this:
Code:
Building::Building()
{
cout << "New building object created.\n";
}
int Building::get_rooms()
{
return rooms;
}