Virtual functions - inheritance query in c++

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

  1. Manarg

    Manarg New Member

    Joined:
    Jun 18, 2007
    Messages:
    10
    Likes Received:
    0
    Trophy Points:
    0
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice