Virtual Functions

closed account (S6k9GNh0)
I'm rather confused as to how virtual functions work. I made this example:

Header (sandbox.h):
1
2
3
4
5
6
7
8
9
10
11
12
#ifndef SANDBOX_H
#define SANDBOX_H

class Sandbox
{
public:
	virtual ~Sandbox() = 0;
	virtual void print_something() =0;
	virtual int return_something() =0;
}

#endif 


Implementation (sandbox.cpp):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "sandbox.h"
#include <iostream>

class SandboxImpl : public Sandbox
{
private:
	virtual ~SandboxImpl();
	virtual void print_something()
	{
		std::cout << "Printing something..." << std::endl;
	}
	
	virtual int return_something()
	{
		return 20;
	}
}


Compiler basically says "screw you" with 500 errors (exactly) and 16 warnings. Did I misunderstand something?
You've made those functions pure virtual (with the =0 on the end), when you declare a function as pure virtual you are telling the compiler that all classes derived from that class must define their own implementation of the virtual functions, and you don't give them a body in the base class.

Oops sorry didn't realise it was derived from Sandbox.

What Xander said...
Last edited on
Well you've missed two semicolons at the end of the class definitions, but I'm guessing that's just the version on here.

I made it compile by doing to following:
1) add the semicolons
2) make the base class's functions public
3) implement the two destructors

Surely it's a problem to make the base class's destructor pure virtual as the inherited destructor calls the base destructor?
EDIT: Nope, it doesn't work... my original statement was correct, not my updated one ;)
Last edited on
The missing semicolons on lines sandbox.h:10 and sandbox.cpp:17 won't help.

I'm not sure if there are any issues with a pure virtual destructor - I've never used one. SandboxImpl doesn't have a destructor defined which will cause a linker error. I'm also not sure what happens if a virtual function is private/protected in a derived class, but public in the base.
Update:
According to an article by Herb Sutter (http://www.gotw.ca/gotw/031.htm ), a destructor can be pure virtual. However, this is only to make the class abstract in the absence of other pure virtual functions, and even a pure virtual destructor must have a body.
Last edited on
closed account (S6k9GNh0)
I see. Thanks for the help.

On a second note, why did GCC go wack? I didn't try this with VC++ but what caused it to give such a messed up error?
Had you missed the semicolons? In larger projects, that tends to cause a lot of errors. The problems with the destructor would probably only actually emerge at link time, not compile time.

EDIT: Also, were the functions in the child class supposed to be private? That struck me as somewhat odd, and if they weren't then that would doubtless cause more errors.
Last edited on
closed account (S6k9GNh0)
I was looking for the pImpl idiom... my bad >.>.
Topic archived. No new replies allowed.