"vj" <va*******@hotmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
|
| Hi! I recently came across this intresting behaviour shown by Visual
| C++ 6.0 compiler regarding Copy Constructors. Please tell me that is
| this the standard behaviour shown by all compilers or its limited only
| to VC++.
Allow me to focus on your class design instead...
|
|
| Listing 1
| ==================
| #include <iostream>
| using namespace std;
| class Class1
| {
| int i;
| public:
| Class1(int ii)
| {i=ii;cout<<"Class1::Parameteized Constructor called with
| "<<ii<<endl;}
|
| int geti(){return i;}
int geti() const
{
return i;
}
see section 18.10 in the faq
http://www.parashift.com/c++-faq-lit...rrectness.html
|
| Class1(Class1 & c)
Class1(const Class1& c)
| {i=c.i;cout<<"Class1::Copy Constructor called with "<<i<<endl;}
|
friend std::ostream& operator<<(std::ostream& os, const Class1& c);
|
| };
|
| ostream & operator<<(ostream & os,Class1 & c)
std::ostream& operator<<(std::ostream& os, const Class1& c)
{
os << c.i;
return os;
}
gee, all of a sudden, you don't even need geti()
| {return os<<c.geti();}
|
| Class1 getNext(Class1 c)
| {Class1 cc(c.geti()+1);
| return cc;
| }
What if getNext(..) attempts to "get" a Class1 node that doesn't exist?
The creator of the class is responsible to supply the appropriate
robustness to cover that eventuality. This should not be left to the
user of the class.
You'ld have a more robust design if you relied on an STL container to
store the instances of Class1 and iterators to get next valid elements.
With iterators, one past the last element in either direction will
evaluate to null. This greatly simplifies your class's design (and
eventually: a container's design).
ie (not tested):
// test.cpp
#include "Class1.h" // without geti() or getNext(...)
#include <iostream>
#include <ostream>
#include <list> // or vector, queue, deque
int main()
{
std::list< Class1 > clist;
clist.push_back(0);
clist.push_back(1);
clist.push_back(2);
// std::copy would be useful here, but for the sake of
// explaining iterators and their benefits...
typedef std::list< Class1 >::iterator CIter;
CIter c_iter = clist.begin(); // where *c_iter is now the first
element
// the for loop remains unchanged regardless of clist's actual size
!
for( c_iter; c_iter != clist.end(); ++c_iter)
{
std::cout << *c_iter << " ";
}
std::endl;
}
<snip>