I haven't noticed this until I tried it today and boom! Compiler complained:
error: constructors cannot be declared virtual

Why then Constructor is not okay while destructor is, in such as class as this?
Thanks

class MyAbstractClass{
	public:
		virtual MyAbstractClass(std::string username, std::string password)=0;
		virtual ~MyAbstractClass(std::string username, std::string password)=0;
		virtual void someOtherMethodsHere()=0;
	
}

Recommended Answers

All 5 Replies

It would be useless to have a virtual constructor in C++. Having a virtual constructor would mean that you could override the class constructor with that of a derived class. Constructors are called at the point of object creation and hence when constructing you cannot be creating a sub-class of the class but the class itself.

I haven't noticed this until I tried it today and boom! Compiler complained:
error: constructors cannot be declared virtual

Why then Constructor is not okay while destructor is, in such as class as this?
Thanks

class MyAbstractClass{
	public:
		virtual MyAbstractClass(std::string username, std::string password)=0;
		virtual ~MyAbstractClass(std::string username, std::string password)=0;
		virtual void someOtherMethodsHere()=0;
	
}

Look up C++ for dummies..good for basic in C++, it helped me a lot.

>>Look up C++ for dummies
HAHAHAHAHA...

We can't inherit constructors, so there is no need for them to be virtual.

commented: That nails it :) +6

Look up C++ for dummies..good for basic in C++, it helped me a lot.

Hahaha, I'm not C++ Dummy, so I don't qualify to read it :)
I know we cannot inherit it so I wanted to know the reason. FP Nailed it, Simply because we cannot Inherit Constructor, why should we override it. That makes sense.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.