Using virtual keyword with class declaration

I was asked in an interview what is the use of a virtual keyword with a class declaration in C ++, and I replied that a virtual keyword cannot be used with a class declaration in C ++. The interviewer said it was possible and asked me to check it later.

Now that I have tested it myself, I found out that it is possible and it is not a compiler error. In fact, when I do something like this with the Visual C ++ compiler:

virtual class Test
{
   int i;
};

      

I am getting a compiler warning "warning C4091:" virtual ": ignored to the left of" Test "when no variable is declared". I have not yet been able to find out what this warning means and further uses the virtual keyword. If there is no useful use, then why is it allowed in the first place and why is it not a compiler error.

+1


a source to share


6 answers


This is a bug in VC ++. Como and gcc both reject the code.



+6


a source


virtual can be used when getting from another class:

class Foo : public virtual Bar
{
}

      



This is used to avoid using multiple versions of the same base class when using multiple inheritance. Wikipedia has a good article on this subject.

+6


a source


You just can't use virtual for classroom. It only works for member functions

+2


a source


You're looking at misuse - I'm pretty sure the interviewer was referring to the virtual base class declarations like:




  class A : virtual public B, public C {
    ...
  };

      



This is a common idiom and is used to work around the "multiple base class" scenario in the pink tree of inheritance. The typical problem with them is that you inherit from both class B and class C and they have a common ancestor A. If you go to the inheritance tree you run into ambiguity as to which instance of "A" you are supposed to be use. If B and C instead have A as a virtual base class, they will refer to the same instance of A, which solves this problem.

You can find a more comprehensive description with class diagrams here .

+2


a source


Perhaps he was referring to virtual inheritance / virtual base classes? For instance.

class A : virtual public B
{ ... }

      

This will technically be part of the class definition.

+1


a source


Can he talk about using a virtual base class in a class declaration?

Like this:

class CashierQueue : virtual public Queue {};

      

This is used in multiple inheritance when you want to avoid a derived class that has multiple copies of an item's data when it inherits from two or more classes that share the same base class.

class Queue {};
class CashierQueue : virtual public Queue {};
class LunchQueue : virtual public Queue {};
class LunchCashierQueue : public LunchQueue, public CashierQueue {};

      

See http://msdn.microsoft.com/en-us/library/wcz57btd(VS.80).aspx

+1


a source







All Articles