copy constructors; why can access private data?

T

thomas

guys, I defined a copy constructor like this.

--code--
FiveTuple::FiveTuple(const FiveTuple &fv_tuple){
source_ip_ = fv_tuple.source_ip_;
dest_ip_ = fv_tuple.dest_ip_;
source_port_ = fv_tuple.source_port_;
dest_port_ = fv_tuple.dest_port_;
ip_protocol_ = fv_tuple.ip_protocol_;
}
--code--

It works.

but the source_ip_, dest_ip_, etc are all private;
How can the copy constructor access private data of fv_tuple directly?
 
A

Alf P. Steinbach

* thomas:
guys, I defined a copy constructor like this.

--code--
FiveTuple::FiveTuple(const FiveTuple &fv_tuple){
source_ip_ = fv_tuple.source_ip_;
dest_ip_ = fv_tuple.dest_ip_;
source_port_ = fv_tuple.source_port_;
dest_port_ = fv_tuple.dest_port_;
ip_protocol_ = fv_tuple.ip_protocol_;
}

You should use a memory initializer list in order to support future
class-type IP addresses, and since apparently this copy constructor does
nothing more or less than the compiler-generated one would do, you
shouldn't really define it in the first place.

--code--

It works.

but the source_ip_, dest_ip_, etc are all private;
How can the copy constructor access private data of fv_tuple directly?

It's a (special) member function.

Member functions have access to private instance data of instances of
the class they're member functions of.


Cheers, & hth.,

- Alf
 
J

Jeff Schwab

thomas said:
guys, I defined a copy constructor like this.

--code--
FiveTuple::FiveTuple(const FiveTuple &fv_tuple){
source_ip_ = fv_tuple.source_ip_;
dest_ip_ = fv_tuple.dest_ip_;
source_port_ = fv_tuple.source_port_;
dest_port_ = fv_tuple.dest_port_;
ip_protocol_ = fv_tuple.ip_protocol_;
}
--code--

It works.

but the source_ip_, dest_ip_, etc are all private;
How can the copy constructor access private data of fv_tuple directly?

Private to the type, not the object.
 
M

Martin York

guys, I defined a copy constructor like this.

--code--
FiveTuple::FiveTuple(const FiveTuple &fv_tuple){
source_ip_ = fv_tuple.source_ip_;
dest_ip_ = fv_tuple.dest_ip_;
source_port_ = fv_tuple.source_port_;
dest_port_ = fv_tuple.dest_port_;
ip_protocol_ = fv_tuple.ip_protocol_;}

--code--

It works.

but the source_ip_, dest_ip_, etc are all private;
How can the copy constructor access private data of fv_tuple directly?

A class is a friend of itself.
Thus one object of class X is able to access the private members of
another object of class X.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top