GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 15-Apr-2004, 02:10
Imajica Imajica is offline
New Member
 
Join Date: Mar 2004
Posts: 1
Imajica is on a distinguished road

Operator overloading & inheritance


How do you overload a single << operator to output members from both the base & derived class?
  #2  
Old 15-Apr-2004, 21:15
machinated machinated is offline
Regular Member
 
Join Date: Mar 2004
Location: victoria, canada
Posts: 324
machinated has a spectacular aura aboutmachinated has a spectacular aura about
i guess you would have that operator defined in the derived class and it would output all the members from the derived class and also it would output the members from the base class. it would access the members from base class using scope resolutor operator :: like so:

CPP / C++ / C Code:

#include <iostream>
using namespace std;

class base
{
protected:
int a, b, c;
public:
	base():a(1),b(2),c(3){}
/* some functions */
};

class derived : public base
{
private:
int a,b,c; //totally different from base class members
public:
	derived():a(4),b(5),c(6){}

/*i've kept things simple by using ++ operator as it is unary. using << for this example 
would complicate things so please do substitute << in your own program as
 it is not recommended to use operators this way. this is just an example */

void operator ++ ()
{
	cout<<a<<b<<c;
	cout<<base::a<<base::b<<base::c;
}
};

int main()
{
	base b;
	derived d;
	++d;
	/* ++d here displays 456123*/
	return 0;
}

this way you only use an operator once on the derived class but make it access or perform operations on the base class as well at the same time. I do wonder tho if anyone would need to do that in the real world, but you never know... I din't really put any thought into this so it's not well planned but it does answer the question. hope it helps
 
 

Recent GIDBlogStupid Management Policies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 01:28.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.