Search code examples
c++functionvirtual

C++ problem with virtual functions


I need to write something in C++. I have problem with virtual functions.

For example, in header file Human.h I have this:

class Human
{
    public:
        virtual int Age();
        Human();
        ~Human();
}

In Human.cpp file I have this:

#include<iostream>
#include "Human.h"

int Human::Age()
{
    return 0;
}

I get these compile errors:

Error    4    error C2371: 'Human::Age' : redefinition; different basic types    c:\users\jan\desktop\testc\testc\human.cpp    5    1    TestC
Error    3    error C2556: 'Human Human::Age(void)' : overloaded function differs only by return type from 'int Human::Age(void)'    c:\users\jan\desktop\testc\testc\human.cpp    5    1    TestC
Error    2    error C2628: 'Human' followed by 'int' is illegal (did you forget a ';'?)    c:\users\jan\desktop\testc\testc\human.cpp    4    1    TestC

Solution

  • You have forgotten to end the class definition with a ;

    It should read

    class Human
    {
    public:
        virtual int Age();
        Human();
        ~Human();
    };
    

    This will likely make the error go away. Also, always read the compiler's output: Error 2 error C2628: 'Human' followed by 'int' is illegal (did you forget a ';'?) c:\users\jan\desktop\testc\testc\human.cpp 4 1 TestC