Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Virtual Functions

Status
Not open for further replies.

Warrioruw

Programmer
Jan 30, 2004
24
CA
Hi all,

I am creating an interface class that will contain virtual functions. The actual implementation of these virtual functions will be created in other classes that specify the functionalities. Simply to say, it's a one-to-many relationship. One interface with virtual functions, many classes that implement virtual functions, even though different classes have functions with same name.

I think it's kind of like inheritance, but not quite sure, and since I don't have much experience, still have some debut and want to know more about this topic. Any help would be appreciated.
 
Everything you said is right. In addition it could be mentioned, that virtual functions are called not directly through function address, but through array of pointers to implementations of virtual functions. That array is filled out only in derived class, there is no sence to use base class without derived class. And here is an example:

// ------------------------ base class definition
class base_class
{
virtual int get_value(void)=NULL;
virtual void set_value(int)=NULL;

public:
void f(void);
};

// ------------------------ base class implementation
void base_class::f(void)
{
set_value(get_value()+1);
}

// ------------------------ derived class definition
class derived_class: public base_class
{
int number;

int get_value(void);
void set_value(int);

public:
int test(void);
};

// ------------------------ derived class implementation
int derived_class::get_value(void)
{
return(number);
}

void derived_class::set_value(int ii)
{
number=ii;
}

int derived_class::test(void)
{
number=1;
f();
return(number);
}

derived_class my_obj;

// ----------------------------
int main(void)
{
printf("%d\n", my_obj.test());
return(0);
}
 
Just a side note: By default, all information in a class is private. The pure virtual functions in "base_class" will not be inherited until you place a "protected:" before them. Also, because they are initialized to NULL (i.e. pure virtual), all classes inheriting from "base_class" MUST define their functionality.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top