Procedural Programming: - Functions Have Been The Main Focus So Far
Procedural Programming: - Functions Have Been The Main Focus So Far
Procedural programming
Functions have been the main focus so far
Function parameters and return values
Exceptions and how the call stack behaves
bool
scoping operator
Point2D::operator< (const Point2D & p2d) const
{
return (x_ < p2d.x_) ||
((x_ == p2d.x_) && (y_ < p2d.y_));
}
CSE 332: C++ Classes
operators
can be
member
functions
as well
The compiler
defines these
4 if you dont*
constructor if any
constructor is declared
Constructors
class Date {
public:
Date ();
};
// default constructor base class /
Date::Date ()
member
: d_(0), m_(0), y_(0)
initialization
{}
list
// copy constructor
Date::Date (const Date &d)
: d_(d.d_), m_(d.m_), y_(d.y_)
{}
// another constructor
Date::Date (int d, int m, int y)
: d_(d), m_(m), y_(y)
{}
constructor body
Access Control
Declaring access control scopes within a class
private: visible only within the class
protected: also visible within derived classes (more later)
public: visible everywhere
Access control in a class is private by default
but, its better style to label access control explicitly
Friend Declarations
Offer a limited way to open up class encapsulation
C++ allows a class to declare its friends
Give access to specific classes or functions
A controlled violation of encapsulation
Friends Example
// in Foo.h
class Foo {
friend ostream &operator<<(ostream &out, const Foo &f);
public:
Class declares operator<< as a friend
Foo(int) {}
Notice operator<< is not a member of class Foo
~Foo() {}
Gives it access to member variable baz
private:
Can now print Foo like a built-in type
int baz;
Foo foo;
};
cout << foo << endl;
ostream &operator<<(ostream &out, const Foo &f);
// in Foo.cpp
ostream &operator<<(ostream &out, const Foo &f) {
out << f.baz; // f.baz is private so need to be friended
return out;
}