virtual class-es

This is a discussion on virtual class-es within the C++ Programming forums, part of the General Programming Boards category; I dont know how to explain to all of you in English.So I m going to show you my problem ...

  1. #1
    Performer
    Join Date
    Jan 2007
    Location
    Macedonia
    Posts
    54

    Question virtual class-es

    I dont know how to explain to all of you in English.So I m going to show you my problem
    Code:
    class Base
    {
    private:
         int x;
    public:
    Base(int xx){x=xx;}
    };
    class Derived1:public Base
    {  
    private:
         int y;
    public:
    Derived1(int xx,int yy):Base(xx)
    { y=yy;}
    };
    class Derived2:public Base
    {
    private:
         int z;
    public:
    Derived2(int xx,int yy):Base(xx)
    { y=yy;}
    };
    class Final:virtual public Deived1,virtual public Derived2
    {
    };
    Why do we write virtual in Final?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Not my arena, but I think it may have to do with the "dreaded diamond".
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Massively Single Player AverageSoftware's Avatar
    Join Date
    May 2007
    Location
    Buffalo, NY
    Posts
    141
    For starters, that's not where you want the virtuals.

    Code:
    class Derived1 : virtual public Base
    {
    };
    
    class Derived2 : virtual public Base
    {
    };
    If you don't do this, the join class (Final in your example) will have two "copies" of Base, the Base it inherited from Derived1, and the Base it inherited from Derived2. Sometimes, this is exactly what you want. Other times it isn't.

    By using virtual inheritance, Final only has one Base component, rather than two.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inherite nonvirtual class functionality
    By DrSnuggles in forum C++ Programming
    Replies: 2
    Last Post: 04-30-2009, 02:52 PM
  2. Virtual base class
    By George2 in forum C++ Programming
    Replies: 7
    Last Post: 03-14-2008, 08:45 AM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Replies: 3
    Last Post: 10-31-2005, 12:05 PM
  5. virtual prototype in a class
    By sphreak in forum C++ Programming
    Replies: 3
    Last Post: 04-01-2004, 02:34 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21