Reputation: 4954
I'm wondering if the following is possible. I wanted my derived class dA
to change func()
to be pure virtual so that any classes derived from dA
must implement func()
.
Code similar to below compiles without complaint under MSVC even though ddA
does not implement func()
.
The compiler does complain about the below code (see comments). So my question now becomes: is this a standards-compliant way to achieve what I want?
class A {
public:
virtual void func() { /* Some base implementation. */ }
}
class dA : public A {
public:
void func() override = 0; // Is this valid?
}
class ddA : public dA {
}
Upvotes: 1
Views: 206
Reputation: 1693
Pure virtual
function should be declared in parent class. Consider the code below:
'''
class Shape {
public:
Shape(int init_x, int init_y) : x(init_x), y(init_y) {}
virtual void scale(int s) = 0;
virtual void print() = 0;
protected:
int x;
int y;
};
These functions should be implemented in children:
class Rect : public Shape {
public:
Rect(int init_x, int init_y, int w, int h);
virtual void scale(int s) { //implementation }
virtual void print() { //implementation }
private:
int width;
int height;
};
However you don't have to implement virtual functions in subclasses since it had been implemented in super class:
Pure virtual function make your class abstract so you can't use its instances.
Upvotes: 1