Pol
Pol

Reputation: 325

Empty virtual function: good practice?

I have a superclass Student, from which Junior class and Senior class inherit.

virtual void student::attend(void){
        //call either Junior's or Senior's attend
        //if attend is called on a Student object, do nothing.
}
 void Junior::attend(void){
    //do stuff
}
 void Senior::attend(void){
  //do stuff
}

Basically my virtual method in the superclass is empty right now, all it does is call the right Senior or Junior attend(). I don't want anything to happen if the object is called on a Student object. The reason I am looking into this is, I want to have something like std::vector <student*> studv where studv will contain both pointers to Senior and Junior and call attend() on every object of the vector without having to specify anything. So, I have two questions:

a) Is this considered good practice? Is there a better alternative? b) Considering one of my classes that inherit the superclass might never make use of one of its functions, what should I do? Should I delete it in the derived class, or just do nothing?

Thanks a lot!

Upvotes: 0

Views: 825

Answers (1)

Tumbleweed53
Tumbleweed53

Reputation: 1551

The real question is whether a student object will ever be created on its own (versus as a subobject of a Junior or Senior). If it won't be created, consider declaring a function which does nothing for a student to be pure virtual:

virtual void attend() = 0;

Then you will not be able to create a student object on its own - you'll get a compiler error if you try - and also, it's self-documenting as to that fact, and nor do you have to provide an empty implementation. Several benefits.

Upvotes: 2

Related Questions