What are Virtual Functions? How to implement virtual functions in "C"

Questions by suji   answers by suji

Showing Answers 1 - 33 of 33 Answers

sukesh narayan

  • Oct 4th, 2005
 

Virtual functio is those function which is basically member function of a base class but define in derrived class .In base class its equal to zero.

For example:

class sum{

public:

void add()=0;

};

class sumderrived{

public:

void add()

{

cout<<"Sum is 10:";

}

};

  Was this answer useful?  Yes

ab79

  • Oct 15th, 2005
 

Virtual functions are those functions of a class which are polymorphic in nature and are declared as :

class Parent {

public: virtual void setVal(int a){ cout<< "calling from Parent"};

}

Virtual functions are overriden in the child classes with the exact same signature in the Parent class.At runtime,depending on the type of the underlying object (i.e if the base pointer points to a base object or a child object), the function corresponding to that object is called.

class Child: public Parent{

void setVal(int b){cout<< Calling from child"};

;

int main(void){

Parent *p,parentObj;

Child childObj;

p=&parentObj;

p.setVal(2);

p=&childObj;

p.setVal(3);

}

In the above example, first p points to parentObj object and hence invokes the setVal() function defined in the Parent class.When the second p.setVal() is called, p points to ChildObj, hence the function setVal() from the Child class is called.

  Was this answer useful?  Yes

Hoang

  • Nov 29th, 2005
 

There is no virtual function in "C" only in "C++". We implement virtual function in order to let derived class to overide this function. If any class defines a pure virtual function, this class is an abstract class.

Haranadh Gupta

  • Jan 5th, 2006
 

Wow really great.

I dont think the key word existed in the C? class inheritance and etc is it available in "C"? Oh... great. First read the question. then post the answer.

  Was this answer useful?  Yes

Brijesh Singh

  • Mar 16th, 2006
 

Maybe we can think of union in "C", which provides sort of polymorphism...

Regards

Brijesh

  Was this answer useful?  Yes

Sujit Kumar Samal

  • Mar 30th, 2006
 

I  request all the member plz post the answer if u r sure that ans is true otherwise not make confuse to other.here laots of ans posted r wrong

In C virtual function is possible.

Keep function pointer in function and use those function pointer to perform operation.

saurabh shrivastava

  • Jan 31st, 2007
 

Hi sudheer could you give some example i am still confuse regarding implementation of virtual function in c

  Was this answer useful?  Yes

Please see my response to the question regarding function overloading. There I described what constitues a function signature and why two functions cannot have exact same signature.

This statement, however, can be proven false in case of polymorphism and virtual functions. Virtual functions are C++'s way of redefining a function/method using the exact same signature.

If a function/method is declared as virtual in a class, that means, the programmer of the class is making a declaration that anyone who would want to inherit another class from this one is free to use the exact same function (including the signature) and redefin its behaviour. This is different from pure virtual function which makes a class an abstract base class preventing it from instantiation without inheritance.

Example of virtual function:
class A{
public:
virtual int myVirtual ( int x) { 
      // Print "Hello from A"
}
};

class B {
public:
// Dynamic Polymorphism
int myVirtual (int x) {
      // Print "Hello from B"
}

// Static Polymorphism or function overloading
int myVirtual (char y) {
     A::myVirtual(1);
}
}; 

void MyFunction()
{
    A a;
    B b;

    a.myVirtual(1); // Prints "Hello from A"
    b.myVirtual(1); // Prints "Hello from B"
    b.myVirtual("a"); // Prints "Hello from A"
}

  Was this answer useful?  Yes

zulfikar Kurane

  • Aug 13th, 2007
 

In C there is not Virtual Functions but we can achieve this functionality by Function Pointer in 'C'. For calling DLL's mostly Function pointer's are used. Function Pointers are more efficient than Virtual functions.

  Was this answer useful?  Yes

ashok

  • Sep 28th, 2007
 

In the above code, you have not inherited Class A into class B. That means there is no question of function overiding. Please correct it to keep your answer valid..

  Was this answer useful?  Yes

williamxhero

  • Nov 6th, 2007
 

#define BASE_ON(X)  X BASE;

struct Person
{
 void (*Smile)();
 void (*Constructor)(void*);
};

void Person_Smile(){printf("This person is smiling");}
void Person_Constructor(void* This){((Person*)This)->Smile = Person_Smile; }

struct Jay{ BASE_ON(Person)
 
 void (*Smile)();
 void (*Constructor)(void*);
};

void Jay_Smile(){printf("Jay is smiling");}
void Jay_Constructor(void* This)
{
 ((Jay*)This)->Smile = Jay_Smile;
 ((Jay*)This)->BASE.Smile = Jay_Smile; // here is the track.
}

#define NEW(Class, Variable)   Class The##Variable;
 Class*  Variable = &The##Variable;
 The##Variable.Constructor= Class##_Constructor;
 The##Variable.Constructor(&The##Variable);

void _tmain(int argc, _TCHAR* argv[])
{
 NEW(Jay, J);
 Person* pP = (Person*)J;
 pP->Smile(); // the output is "Jay is smiling", regardless the pP is a (Person*).
}



/* since this is C, so there are hell of worka should be done by yourself. and also you know that C++ compiler did a lot of jobs for you...
*/

  Was this answer useful?  Yes

Sukesh,
Your response is essentially correct if we are talking about pure virtual
functions. However, when we talk about virtual functions, then we perhaps need
to make a distinction between regular virtual functions and pure virtual
functions. The example in my earlier response has a slight (yet significant)
error. So, here’s the updated example.


Example of virtual function:
class MyBaseClass {
public:
int MyVirtualFunction (int x) {
// Print “Hello World from MyBaseClass
return 1;
}
};
class MyChildClass: public MyBaseClass {
public:
int MyVirtualFunction (int x) {
// Print “Hello World from MyChildClass
return 1;
}
};
int main(int x)
{
MyBaseClass mbc; // Runtime type = MyBaseClass
MyChildClass mcc; // Runtime type = MyBaseClass
mbc.MyVirtualFunction (1); // prints Hello World from MyBaseClass
mcc.MyVirtualFunction (2); // prints Hello World from MyChildClass
return 1;
}
End Example
-----------------


In the above example, if the MyVirtualFunction in the MyBaseClass was defined
as follows:
Int MyVirtualFunction (int x) = 0; // pure virtual function
That would have made the MyBaseClass an abstract base class.
In that case, the first executable line in the main function (MyBaseClass mbc;)
would have generated an error because you cannot instantiate a virtual base
class (or an abstract base class).
However, the second one would still be possible (MyChildClass mcc;) because the
MyVirtualFunction has a body (definition) in the child class.


Bottom line –
Virtual functions provide the ability to redefine the behavior of the same
method in child class, thereby providing a different behavior than the parent.
Pure virtual functions – do not have any behavior and hence render the class in
which they live unusable for direct instantiation. The classes that have pure
virtual functions need to have a child class in which the pure virtual functions
are defined (given a behavior) before any instances can be created.

  Was this answer useful?  Yes

kamranahmad

  • May 25th, 2008
 

Hi
here i have more simplified example Hope this will give you clear view
and check this link

http://www.codersource.net/published/view/325/virtual_functions_in.aspx

#include <stdio.h>
#include <stdlib.h>
#define BASE_ON(X)  X BASE;

typedef struct
{
    long _objID;
    void (*Smile)();        //like virtual function
    void (*Constructor)(void*);    //like constructor
}Person;

void Person_Smile()
{
    printf("This person is smiling in base classn");
}
void Person_Constructor(void* This)    //like Constructor of Person class
{
    ((Person*)This)->Smile = Person_Smile;
}

Person *newPInstance(long oID)            //mem allocation function for person class like New in C++
{
    Person *pClass = (Person *)malloc(sizeof (Person) );

    if (pClass)
    {
        pClass->_objID = oID;                //assigning ID
        pClass->Constructor= Person_Constructor;    //assigning Constructor
        pClass->Constructor(pClass);            //Invoking Constructor
    }
    return pClass;
}

typedef struct
{
    BASE_ON(Person)
 
    void (*Smile)();            //like virtual function
    void (*Constructor)(void*);        //like Constructor
}Jay;

void Jay_Smile()            //virtual function implementation in drived class
{
    printf("Jay is smiling in drived classn");
}

void Jay_Constructor(void* This)        //drived class Jay constructor
{
 ((Jay*)This)->Smile = Jay_Smile;        //assigning Jay_Smile to drived class function
 ((Jay*)This)->BASE.Smile = Jay_Smile;         //assigning Jay_Smill to Base class function.
}

Jay *newJInstance(long oID)            //Mem allocator function for Jay like New in C++
{
    Jay *jClass = (Jay *)malloc(sizeof (Jay) );

    if (jClass)
    {
        jClass->BASE._objID = oID;        //assiging id
        jClass->Constructor=Jay_Constructor;    //assigning Constructor
        jClass->Constructor(jClass);        //Invoking Constructor
    }
    return jClass;
}


int main()
{
    Jay *J = newJInstance(100);

    Person* pP = (Person*)J;
    pP->Smile();

    Person* p2 = newPInstance(200);
    p2->Smile();

    p2->Smile=pP->Smile;
    p2->Smile();
   
    free(J);
    free(p2);
    return 1;
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions