Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

c++ virtual functions

Options
  • 10-12-2009 1:07am
    #1
    Registered Users Posts: 9,126 ✭✭✭


    I have an exam in c++ tomorrow morning and there's a question that's likely to appear on it that I really don't know how to do.
    class A {
    public:
    	void f(){
    		cout << "f" << endl;
    		g();
    		}
    	virtual void g(){
    		cout << "g" << endl;
    	}
    };
    

    How do I write a main program for that so that A::f is executed but A::g is not? Any help would be much appreciated.


Comments

  • Closed Accounts Posts: 1,397 ✭✭✭Herbal Deity


    virtual just means overridable...

    You could write a class "B" which inherits from A, and override g() such that it does nothing, and then when you call B::f(), when it calls g() nothing happens instead of it printing "g".

    But ultimately, I don't understand your question 100%.


  • Registered Users Posts: 9,126 ✭✭✭Royale with Cheese


    Sorry the print statements I added myself just so I could see what was happening. I thought about using a subclass to override f() so that it doesn't call g() but that seemed liked cheating.

    This is the question as it appears in the exam:

    cquestion.png


  • Registered Users Posts: 267 ✭✭Tears in Rain


    Make a subclass of A called B

    B over-rides A::g() with a new function called B::g()

    Thus, when an instance b of B is created, and we call b.f(), the following functions are called in turn:

    A::f()
    B::g()

    And that is your solution.


Advertisement