1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Virtual functions - inheritance query in c++

Discussion in 'C++' started by Manarg, Dec 30, 2007.

  1. Manarg

    Manarg New Member

    Hello, i'm now learning c++ and i want to ask this:
    Suppose that we have these three classes:
    Code:
    class A {
    private: 
                 int sth;
                 //.....
    public:
                 virtual int is_class_B (void) = 0;
                 void print (void)  { cout << "I'm in class A" << endl; return;}
                 int get_sth (void) { return sth; }
                 //.......
    };
    
    class B : public A  {
    private: //......
    public:
                 int is_class_B (void) { return 1; }
                 void print (void) { cout << "I'm in class B" << endl; return; }
    };
    
    class C : public A {
    private: //........
    public:
                 int is_class_B (void) { return 0; }
                 void print (void) { cout <<"I'm in class C" << endl; return; }
    };
    
    We also have a class A * that points to either a class B object or a class C object (lets call him classptr). I want to make a function that can be described in a pseudo-language like this:
    Code:
    switch (classptr.get_sth ()) {
                 case 0: 
                              classptr.print (); // use the print func of class A
                              break;
                 default:
                              if (classptr.is_class_B ()) {
                                          classptr.print (); // use the print func of class B
                                          // .....
                              }
                              else {
                                           classptr.print (); // use the print func of class C
                                           // ........
                              }
                              break;
    }
    
    My question is: How can i choose which print will be used in each case? For example the classptr can point to a class B object but if classptr.sth == 0 i want to use the print function of class A, not this of the derived class. On the other hand, if sth != 0 i want to use the print function of the derived class. Do you have any ideas? Thanx in advance for the help & sorry for any english mispelling!
     

Share This Page