Thread: Correct model? Virtual functions.

  1. #1
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152

    Correct model? Virtual functions.

    Hi, I would explain what I want to do, but I think that the code explains better. Basically, I need that an initialization and finalization code are executed before (and after) different other functions (sorry, very bad explanation), here is the code:
    Code:
    #include <iostream>
    
    using namespace std;
    
    class A {
    public:
    		void action() {
    				cout << "Before update." << endl;
    				update();
    				cout <<	"After update." << endl;			
    		}
    
    		virtual void update() {
    				cout << "Updating class A." << endl;
    		}		
    };
    
    
    class B : public A {
    public:
    		void update() {
    				cout << "Updating class B." << endl;
    		}
    };
    
    
    class C : public A {
    public:
    		void update() {
    				cout << "Updating class C." << endl;
    		}
    };
    
    int main()
    {
    		C c;
    		B b;
    
    		b.action();
    		c.action();
    
    		return 0;
    }
    Is this code "portable" and "right"?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Is this code "portable" and "right"?
    Yes.

    In fact, it is a recommended way of using polymorphism (see C++ Coding Standards Item #39). You would want to make update private or protected, though. Then what you are doing is exposing only the non-virtual action member function to users of the A hierarchy. Then you implement action() with virtual functions. Even if action() didn't have any other code than calling private or protected virtual methods, it would still make sense to do it that way.

    Don't forget to make A's destructor virtual. Also, a better example of usage might be this since it uses B and C polymorphically:
    Code:
    void DoWork(A& a)
    {
    	a.action();
    }
    
    int main()
    {
    	C c;
    	B b;
    
    	DoWork(b);
    	DoWork(c);
    
    	return 0;
    }
    Last edited by Daved; 06-25-2007 at 11:14 AM.

  3. #3
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Thanks very much! =)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 48
    Last Post: 09-26-2008, 03:45 AM
  2. Replies: 2
    Last Post: 10-02-2005, 05:04 PM
  3. (uninteresting) parsing and virtual functions
    By ggs in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 03-19-2002, 06:07 PM
  4. virtual functions.
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 03-07-2002, 09:07 PM
  5. inheritance & virtual functions
    By xagiber in forum C++ Programming
    Replies: 3
    Last Post: 02-11-2002, 12:10 PM