Asked  11 Months ago    Answers:  5   Viewed   180 times

Possible Duplicate:
Can someone explain C++ Virtual Methods?

I have a question regarding to the C++ virtual functions.

Why and when do we use virtual functions? Can anyone give me a real time implementation or use of virtual functions?



You use virtual functions when you want to override a certain behavior (read method) for your derived class rather than the one implemented for the base class and you want to do so at run-time through a pointer to the base class.

The classic example is when you have a base class called Shape and concrete shapes (classes) that derive from it. Each concrete class overrides (implements a virtual method) called Draw().

The class hierarchy is as follows:

The following snippet shows the usage of the example; it creates an array of Shape class pointers wherein each points to a distinct derived class object. At run-time, invoking the Draw() method results in the calling of the method overridden by that derived class and the particular Shape is drawn (or rendered).

Shape *basep[] = { &line_obj, &tri_obj,
                   &rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
    basep[i] -> Draw ();

The above program just uses the pointer to the base class to store addresses of the derived class objects. This provides a loose coupling because the program does not have to change drastically if a new concrete derived class of shape is added anytime. The reason is that there are minimal code segments that actually use (depend) on the concrete Shape type.

The above is a good example of the Open Closed Principle of the famous SOLID design principles.

Saturday, July 10, 2021

Since g++ 4.7 it does understand the new C++11 override keyword:

class child : public parent {
      // force handle_event to override a existing function in parent
      // error out if the function with the correct signature does not exist
      void handle_event(int something) override;
Sunday, June 27, 2021

Because if you pass by value, then object slicing will occur, and runtime polymorphism cannot be achieved. And in your code, the very line Material m = Texture() causes object slicing. So even if you pass m by pointer (or reference), runtime polymorphism cannot be achieved.

Also, runtime polymorphism is achieved through:

  • pointer of base type, or
  • reference of base type

So if you want runtime polymorphism, you've use either pointer or reference of base type, and here are few examples how you can achieve runtime polymorphism:

Material* m1 = new Texture();
poly->setMaterial(m1);     //achieved

Texture* t1= new Texture();
poly->setMaterial(t1);     //achieved

Texture t2;
poly->setMaterial( &t2);   //achieved : notice '&'

Material & m2 =  t2;
poly->setMaterial( &m2 );  //achieved : notice '&'

Material  m3;
poly->setMaterial( &m3 );  //NOT achieved : notice '&'

Only in the last line you don't achieve runtime polymorphism.

Thursday, August 12, 2021

A common way to implement virtual functions is to have a pointer to a "virtual table" or vtable at a negative offset from the object. This table is needed to figure out what virtual function to call. This is why just malloc'ing space doesn't work.

Tuesday, August 17, 2021

I think you might be asking how to declare a method that will be implemented some time later somewhere else.

The Objective-C way to do that is to use Protocols.

You declare a protocol like this, usually in a header file

@protocol MyProtocol <NSObject> {
    - (void)optionalMethod;
    - (void)requiredMethod;

This declares two methods, one which is optional and one is required. To use this protocol you declare the conformance when declaring the class that will implement the protocol

@interface MyConformingClass : NSObject <MyProtocol> {
// you don't have to redeclare methods that are declared in the protocol

This new class is checked at compile time for the implementation of requiredMethod so it has to implement it, but it can choose whether or not to implement the optionalMethod

Now, any class that requires instances of objects to conform to the protocol can declare this, for example, in the interface

@interface RequiringClass : NSObject {
    MyConformingClass <MyProtocol> *conformingClassObject;

Again, this is checked at compile time

To make sure that the conforming class implement the @optional methods, we can use this handy structure

if [conformingClassObject respondsToSelector:@selector(optionalMethod)] {
    [conformingClassObject optionalMethod];
} else {
    // Do something here because the optional method isn't provided

Examples of this are all over Cocoa - it's a class can provide a list of actions that it would like to farm out to it's delegate, the delegate adopts the protocol and provides the implementations of those delegate methods. The calling object can then check if this delegate responds to those methods at runtime as I've described above, and call those methods to perform actions, or provide information where ever it needs to.

This is used quite a lot in Objective-C, where classes provide a list of methods that they would like some other class to perform, unlike virtual functions, where a class declares functions it wants subclasses to provide implementations for. Particularly as Composition is favoured over inheritance in the language. Rather than create a subclass to provide an implementation, you just create another class that can do the same thing, and add a reference to that in the class instead.

Friday, December 10, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :