Download presentation
Presentation is loading. Please wait.
Published bySuparman Tedjo Modified over 5 years ago
5
const A& B::blah (const C& c) const {...}
Passed in a reference to a constant object ‘c’ ‘c’ cannot be modified in the function const A& B::blah (const C& c) const {...} Return a reference to a constant object The returned object can then only call constant methods This is a constant method, meaning this object is treated as a constant during this function None of its data members can be modified
6
Making “friends” between classes
When a data member is declared “private”, all the other classes cannot access it directly Must call through “member functions” Unless, declare myself (MyClass) as “friend” of other class (OtherClass) class MyClass { friend class OtherClass; ... }; OtherClass can access MyClass’s data members OtherClass::f() { ...; myClassObj._myClassData; ... } Not recommended (unless no better way)
7
Common usage of friend class
If some class A is designed specifically for another certain class B, and is intended to hide from others... Making A a friend class to B For example, class ListNode { friend class List; ... }; class List ListNode* _head; T& front() { return *(_head); }
8
Friend of a Member Function
Instead of making MyClass as friend to the whole OtherClass, however, we can make friend with only certain member functions in OtherClass e.g. class MyClass { friend void OtherClass::setData (const MyClass&); int _db; ... }; void OtherClass::setData(const MyClass& b) { _da = b._db; } (See also) Operator overload * .../refSrc/lec03/friend1.cpp
13
Pay attention to the function prototypes below...
T& operator = (const T& v); T& operator [] (size_type i); const T& operator [] (size_type i) const; T operator ~ () const; // also for -, &, |, etc T& operator ++(); // ++v T operator ++(int); // v++ T operator + (const T& v) const; // also for -,*,&,etc T& operator += (const T& v); // also for -=,*=,&=,etc bool operator == (const T& v) const; //also for !=, etc friend ostream& operator << (ostream&, const T&); The operator ‘()’ can also be overloaded and used as “generator”
14
T& operator = (const T& v);
15
T& operator [] (size_type i)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.