Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Virtual functions - inheritance query in c++ (http://www.go4expert.com/forums/virtual-functions-inheritance-query-cpp-t8035/)

Manarg 30Dec2007 07:06

Virtual functions - inheritance query in c++
 
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!


All times are GMT +5.5. The time now is 20:35.