How to define a virtual class member function in .cpp file that is declared in .h file
Feb 23, 2017 at 8:38pm UTC
Hi, I am trying to put all class declarations in .h file and all definitions in .cpp files.
But I am unable to define virtual class member functions in this way and getting error :
String.cpp:33:1: error: ‘virtual’ outside class declaration
virtual String::~String()
String.h
1 2 3 4 5 6 7 8 9 10 11 12
#include <cstring>
class String
{
private :
size_t size;
char *charString;
public :
String();
virtual ~String();
};
String.cpp
1 2 3 4 5 6
String::String() : size(0), charString(NULL) {}
virtual String::~String()
{
delete charString;
}
Feb 23, 2017 at 8:45pm UTC
You need the virtual keyword only inside the class declaration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
class object
{
public :
virtual void x();
};
void object::x()
{
std::wcout<<L"Object called\n" ;
}
class derived: public object
{
public :
void x();
};
void derived::x()
{
std::wcout<<L"Derived called\n" ;
}
int main()
{
object * obj=new derived();
obj->x();
return EXIT_SUCCESS;
}
Output:
Also, inside the destructor you may want to use the following:
1 2 3 4
String::~String()
{
delete [] charString;
}
Last edited on Feb 23, 2017 at 8:51pm UTC
Feb 23, 2017 at 8:47pm UTC
Thanks @Golden Lizard :)
Topic archived. No new replies allowed.