2-C++ OO Programming

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 39

II.

C++ object oriented


- Classes & objects
- Constructors & destructor, class functions
- Access modifiers
- Friend function & friend class
- Inheritance & Access modes
- Class: function overriding
- Class: function/operator overloading

Nguyễn Anh Hào  0913609730 [email protected]


2
Class & object in programming
 Everywhere you look in the real world you see objects—people,
animals, plants, cars, planes, buildings, computers and so on.
Objects have some things in common:
 They all have attributes (e.g., size, shape, color and weight)
 They all exhibit behaviors (e.g., a ball rolls, bounces, inflates
and deflates; a baby cries, sleeps, jumps up and down).
 Humans learn about existing objects by studying their attributes
and observing their behaviors.
 Ex, comparisons can be made between baby and ball.
 Object-oriented design and implementation (programming)
provide a natural way to create softwares—that is, modeling
objects by their attributes and behaviors (class) just as we
understand and describe the real-world objects (classification)
 It's very important to share the programming ideas.
3
C++ Class
 A class is a user-defined type, like a struct in C++.
 A class consists of a set of members:
 Data members,
 Member functions,
 Other classes ("nested"), ... and friends
 Members are accessed using . (dot), or −> (arrow)
 Member functions can define the initialization (constructors),
tasks for the class-responsibility, and cleanup (destructor) with
function overloading.
 The acccess modifiers: public, private or protected to the
members.
 A class inherits from another class with access mode.
 An inherited function can be overriden.
 A class can be accessed fully by friends.
4
C++ Class declaration
 A class is defined using keyword class followed by its name
class Account // <--- Account is class name
{ private: // <--- access modifier, is a keyword
string Usr, Pw; // <--- private data members: Usr, Pw
public: // <--- access modifier
// its public member functions:
Account(string u, string p) {Usr = u; Pw = p;} //<--constructor
SetAcc (string u, string p) { Usr = u; Pw = p; }
bool Check(string u, string p) {return (Usr==u) && (Pw==p);}
}; // <--- after class Account {...}, the semicolone (;) is a must !
 It is the same as struct, the only difference is: all the members
of class are private by default, instead of public as in struct.
 When a class is declared as above, only the specification for the
object is defined, no memory is allocated for class.
5
Class member access operators
 With the previous class Account:
class Account
{ //...
public:
SetAcc (string u, string p) { Usr = u; Pw = p; } // member
//...
};
// Now, declare an object:
Account MyAcc; // notice: no need of 'class' keyword
 MyAcc is an object, memory allocated, we can access it
1.Direct member selection: '.' (dot operator)
MyAcc.SetAcc ("me", "abc");
2.Indirect member selection: '->' (pointer operator)
Account *p = &MyAcc; // p is a pointer pointing to MyAcc
p->SetAcc ("me", "abc"); // Or, (*p).SetAcc("me","abc");
6
Class constructors
 A class constructor is a method that is invoked automatically at
the time object is created. It is used to initialize the data
members of new objects, example:

class Fraction P2-ClassFraction1.cpp


{ public:
int numerator, denominator;
Fraction( int n=0, int d=1 ) // default: n = 0, d =1
{ numerator=n; denominator=d; }
Fraction(const Fraction &p)
{ numerator=p.numerator; denominator=p.denominator; }
Fraction (double a) // another constructor...
{ numerator = round(a*100); denominator = 100; }
};
Fraction P1,P2(1), P3(1,2); // P1=0/1, P2=1/1, P3=1/2
Fraction P4(P3); // P4 = P3 = 1/2
7
Class destructor
 Class destructor is the only member function invoked
automatically whenever an object of this class is going to be
destroyed, example:

class Fraction
{ // class members...
~Fraction() // <--- destructor
{ // do something before object is destroyed
cout << "** obbject is going to be destroyed" << end;
}
};
int main()
{ Fraction P5; // P5 is created
return 0; //-->screen:** obbject is going to be destroyed
}
8
Class functions
 Fraction Obj;
 Obj.add1(p1,p2) returns a new fraction (p1 + p2)
P2-ClassFraction2.cpp
class Fraction
{ public:
int numerator, denominator;
Fraction (int n=0, int d=1) { numerator=n; denominator=d;}
Fraction add1(Fraction p1, Fraction p2)
{ Fraction p3; // create new object p3, p3 = p1 + p2
p3.numerator = p1.numerator*p2.denominator
+ p2.numerator*p1.denominator,
p3.denominator= p1.denominator * p2.denominator;
// should we do simplifying p3 ? do it !
return p3;
}
};
9
Class functions
class Fraction
{ public:
int numerator, denominator;
Fraction (int n=0, int d=1) { numerator=n; denominator=d;}
Fraction add1(Fraction, Fraction); // it's just a prototype
};

// we can implement 'add1' method outside of the class:


Fraction Fraction::add1(Fraction p1, Fraction p2)
{ Fraction p3;
p3.numerator = p1.numerator*p2.denominator
+ p2.numerator*p1.denominator,
p3.denominator= p1.denominator * p2.denominator;
}
10
Class functions
 Fraction Obj; Obj.add2(p) returns (Obj + p)
class Fraction P2-ClassFraction2.cpp
{ public:
int numerator, denominator;
Fraction (int n=0, int d=1) { numerator=n; denominator=d;}
Fraction add2 (Fraction p)
{ Fraction p3;
p3.numerator = numerator*p.denominator
+ p.numerator*denominator,
p3.denominator = denominator * p.denominator;
return p3;
}
};
Fraction a(1,2), b(1,3), c = a.add2(b); // c = a + b = 1/2 + 1/3
11
Class functions
 Fraction Obj; Obj.add3(p) adds p to this Obj
P2-ClassFraction2.cpp
class Fraction
{ public:
int numerator, denominator;
Fraction (int n=0, int d=1) { numerator=n; denominator=d;}
add3(Fraction p)
{ numerator = numerator*p.denominator
+ p.numerator*denominator,
denominator = denominator * p.denominator;
}
};

Fraction a(1,2), b(1,3); a.add3(b); // a = a + b = 1/2 + 1/3


12
Class & Object: This pointer
 We can create multiple instant objects (with data members and
member functions) of the same class:
 Fraction p1(1,1), p2(1,2), p3(1,3),.. each pi is an object
 Each object gets its own data members, but all the objects
access the same function of the class in the memory:
 add3(Fraction) is accessed from object p1,p2,p3,...
 If an object p1 accesses to its common member function add3,
how can add3 identify p1's data exactly ?
 add3(Fraction) { /* what object'data is accessing ? */ }
 The this pointer, only used in member function, is pointing to
the class instance (object) to help member function identifying
the object's data:
 add3(Fraction) { this->numerator = ... }
13
This pointer usage
1. When a local variable’s name is the same as member’s
name (the same named variables are in the same scope !)

class Fraction P2-ClassFraction3.cpp


{ public:
int numerator, denominator;
//notice: parameter's name is the same as of data member
Fraction(int numerator, int denominator)
{ this->numerator = numerator;
this->denominator = denominator;
}
}
14
This pointer usage
2. To return reference to the calling object

class Fraction P2-ClassFraction3.cpp


{ public:
int numerator, denominator;
Fraction& SetN(int n) { this->numerator = n; return *this; }
Fraction& SetD(int d) { this->denominator = d; return *this; }
}

Fraction p;
p.SetN(1).SetD(2); // p(1,2)

/* SetN(1).SetD(2) = 'Chained function calls', all calls modify the


same object as this object is returned by reference */
15
This pointer usage
3. The this pointer is also used to guard against self-
reference

class Fraction P2-ClassFraction3.cpp


{ public:
int numerator, denominator;
Fraction& Subtract(Fraction &p) // calculate (this - p)
{
if (&p == this) /* p is the object accessing to Subtract() */
{ /* do something */
} else /* p is not the object accessing to Subtract() */
{ /* do other things */
}
}
}
16
Access modifiers
 The access modifiers (or specifiers) of C++ are public,
private, and protected, used for data hiding: restrict
access to the members of the class.
 public: The public members are accessible from any part of
the program.
 private: The private members can be accessed from within
the class only. All the member functions have full access to
them.
 protected: The protected members can be accessed within
the class, and from the derived class (child class).
17
Class access: from the outside
class Base
{ private: int a; P2-AccessModifiers.cpp
protected: int b;
public: int c;
Init () { a =1; b =2; c =3; } // OK, Init() has full access
};
int main()
{ Base B; B.Init();
int x = B.a; // Error
int y = B.b; // Error
int z = B.c; // OK
return 0;
}
Can the private & protected members be accessed from outside of class ?
18
Class: friend function
 A friend function has access to all the members of a class with
keyword friend, but it is not a member of this class.
class Point3D P2-friendFunction.cpp
{ private: float x; float y; float z;
public: void Set(float px, float py, float pz) { /*... */ }
};
class Point2D
{ private: float x; float y;
public: void Set (float px, float py) { x = px; y=py; }
friend Point3D To3D(Point2D); // <-- allow friend function
};
Point3D To3D(Point2D p2)
{ Point3D p3;
p3.Set(p2.x, p2.y, 0); //<-- read p2 private members
return p3;
}
19
Class: friend class
 friend class: All the member functions of the friend class
become friend functions.

class Point2D P2-friendClass.cpp


{ private: float x, y;
friend class Line2D; // <-- allow friend class
};

class Line2D
{
public:
float Distance(Point2D p1, Point2D p2){/*read (x,y) of p1,p2 */}
Point2D Middle(Point2D p1, Point2D p2){ /*...*/ }
}
20
Class inheritance
 Inheritance is the ability to create a derived class (child
class) from an existing one (base, or parent class).

 The child class typically inherits the data members and


methods of the parent class, although it can also redefine
them (override).

 Class inheritance allows developers to reuse code (from


base classes), and easily add new features (data members
and methods to derived classes).
21
Class inheritance in C++
 A derived class (the child) can inherit data members and
member functions from an existing base class (the parent)
class Vehicle
{ public:
int Seats; // number of seats
int Speed; // maximum speed
private:
string Engine;
};
class Bus : public Vehicle { Bus() {Seats=50; Speed=80;} };
class Car : public Vehicle { Car() {Seats=7; Speed=250;} };
class Bike : public Vehicle { Bike() {Seats=2; Speed=50;} };
// the : is a notation means 'inherit from'
// Seats & Speed are inheritted, Engine is NOT (private)
// what does public mean ? public is an access mode...
22
Access mode & access modifier
 Access mode redefines accessibility to inherited members
Derived-class : Access-mode Base-class

private protected public


Base class:
modifier modifier modifier

private inherited as inherited as


No inherit
access mode private private

Derived protected inherited as inherited as


No inherit
class: access mode protected protected

public inherited as inherited as


No inherit
access mode protected public
23
Access mode
Access mode =
 private : all the members of the base class become private
members in the derived class.
 Base:public access modifier ->Derived:private access modifier
 Base:protected access modifier ->Derived:private access modifier

 protected: The protected & public members of the base class


become protected members in the derived class
 Base: public access modifier -> Derived: protected access modifier

 public : all the members of the base class (exclude private


members) are inherited by the derived class just as they are.
24
Access mode & access modifier
class Base
{ private: int a;
protected: int b;
public: int c;
};
class Child1 : public Base
{ // a: not inherit, b: as protected, c: as public
};
class Child2 : protected Base
{ // a: not inherit, b: as protected, c: as protected
};
class Child3 : private Base
{ // a: not inherit, b: as private, c: as private
};
25
Class access: from derived class
class Base
{ private: int a; P2-AccessModifiers.cpp
protected: int b;
public: int c;
Init () { a =1; b =2; c =3; }
};

class Child : public Base // Child is fully inherited from Base


{ public:
void access_a() {int x = a;} // Error
void access_b() {int x = b;} // OK, with public access mode
void access_c() {int x = c;} // OK
};
26
Class: Multiple Inheritance
 Multilevel Inheritance: A class can also be derived from
one class, which is already derived from another class
 Class A; class B: public A; class C: public B,...

 Multiple Inheritance: A class can also be derived from


more than one base class
 Class A; class B; class C: public A, public B
27
Class: Multiple Inheritance ex.
class Mammal // P2-MultipleInheritance.cpp
{ public:
Mammal() { cout << "I can give direct birth."; }
void move() { cout << "I run on my legs."; }
};
class WingedAnimal
{ public:
WingedAnimal() { cout << "I can flap."; }
void move() { cout<< "I fly."; }
};
class Bat: public Mammal, public WingedAnimal {};

Bat b1; // I can give direct birth.I can flap.


b1.move(); // Error! Ambiguity: which function to call ?
b1.WingedAnimal::move(); // using scope resolution ::, it's OK
28
Class inheritance: function overriding
 If the same function is defined in both based class and derived
class, and if the function is called from the object of derived
class, the function of the derived class (different behavior) is
executed, instead of the base class's.
P2-FunctionOverriding.cpp
class Base
{ public: void Print() { cout << "Base Function" << endl; }
};
class Derived : public Base
{ public: void Print() { cout << "Derived Function" << endl; }
};
int main()
{ Derived derived1;
derived1.Print(); // access Print() of the Derived class
return 0;
}
29
Accessing overridden function
 To access the overridden function of the base class, we
use the scope resolution operator ::

class Base P2-FunctionOverriding.cpp


{ public: void Print() { cout << "Base Function" << endl; }
};
class Derived : public Base
{ public: void Print() { cout << "Derived Function" << endl; }
};
int main()
{ Derived derived1;
derived1.Print(); // access print() of the Derived class
derived1.Base::Print(); // access print() of the Base class
return 0;
}
30
Function overloading vs overriding
FUNCTION OVERLOADING
FUNCTION OVERRIDING

  The
Thesame
samename
nameand
andtype
type

  Different
The same parametters
parametters (=>
but different behaviors.
different behaviors)
 int baseclass::fn(int a)
  int
intfnderived::fn(int
(int a) a)
 int fn (int a, int b)
 Different scope
 The same scope
 baseclass <> derived class
 In the same block { },..
 Need inheritance
 Don't need inheritance
31
Class: function overloading
class Fraction
{ //....
P2-FunctionOverload.cpp
Fraction Add (int n)
{ int n2 = numerator+n*denominator, d = denominator;
Fraction q( n2, d ); return q;
}
Fraction Add (Fraction p) // Add() is overloaded
{ Fraction
q(numerator*p.denominator+p.numerator*denominator,
denominator * p.denominator); return q;
}
Fraction Add (double a) // Add() is overloaded
{ Fraction q(round(a*100),100); return Add(q); // which Add() ?
}
};
Fraction a(1,2); Fraction c = a.Add(2); // 1/2 + 2 = 5/2
Fraction b(1,3); c = b.Add(0.15); // 1/3 + 0.15
32
Class: operator overloading
 Fraction a(1,2); a+2 is more expressive than a.Add(2). That's
why we need operator (+,-,...) overloading for user define type
like class or struct.

 Syntax for C++ Operator Overloading:


class className
{ public:
returnType operator symbol (arguments)
{
/* overloading code for the operator */
}
};
 returnType is the return type of the overloading operator
 operator is a keyword
 symbol is the operator like +, <, -, ++, etc...
 arguments is the arguments passed to the operator
33
Ex: Binary arithmetic (+) overloading
P2-OperatorOverload1.cpp
class Fraction
{ //....
Fraction (double a) // constructor
{ numerator = round(a*100); denominator = 100; }
Fraction add(Fraction p) { /* returns this fraction + p */ }
Fraction operator+ (Fraction p) // operator + overloading
{ return this->add(p); }
Fraction operator+ (double a) // operator + overloading
{ Fraction p(a); // convert double a to fraction p
return this->add(p); }
};

Fraction a(1,2), b(1,3), c = a+b; c = a+0.25;


34
Ex: Increment (++) overloading
class TimeEn P2-OperatorOverload3.cpp
{ private:
unsigned h, m, s;
void Inc1Sec(); // increase 1s for TimeEn obj
public:
TimeEn(int hh=0, int mm=0, int ss=0) // constructor
{ h = hh; m = mm; s = ss; }
TimeEn operator ++() // Overload PREFIX operator ++(obj)
{ Inc1Sec(); return * this; }
TimeEn operator ++(int) //POSTFIX (obj)++. (int) is syntax !
{ TimeEn tmp=*this; Inc1Sec(); return tmp; }
} Tm(0,0,0);

TimeTn t2 = Tm ++; //POSTFIX syntax


TimeTn t1 = ++ Tm; //PREFIX syntax. What is the difference ?
35
Ex: Comperator (==) overloading
P2-OperatorOverload4.cpp
class Fraction
{ // ....
bool operator== (Fraction p)
{ return (this->numerator*p.denominator
== this->denominator*p.numerator);
}
bool operator!= (constant Fraction &p) // just use reference
{ return (this->numerator*p.denominator
!= this->denominator*p.numerator);
}
// can u overload operators >, <, ... ?
};
Fraction a(1,2), b(2,4);
if (a==b) cout << "a equals b";
36
Ex: cout << overloading
The cout is an ostream object with overloaded operator << (is
left shift bit, or bitwise, operator) as an output operator for each
basic type like int, string,...; we can also overload it for our type:
class TimeEn
{ private: P2-OperatorOverload5.cpp
unsigned h, m, s;
public:
friend ostream& operator << (ostream&, const TimeEn&);
};
// overloading operator << for TimeEn Obj:
ostream& operator << (ostream &os, const TimeEn& t)
{ os << t.h << ':' << t.m << ':' << t.s;
return os;
}
TimeEn t(0,0,1); cout << "Time is " << t; // Time is 0:0:1
37
Ex: cin >> overloading
 Like cout <<, the cin >> can be overloaded for our type:
class TimeEn
{ private: P2-OperatorOverload5.cpp
unsigned h, m, s;
public:
friend ostream& operator << (ostream&, const TimeEn&);
friend istream& operator >> (istream&, TimeEn&);
};
istream& operator >> (istream &is, TimeEn& t)
{ is >> t.h >> t.m >> t.s;
return is;
}

TimeEn t;
cin >> t; // 08<enter>10<enter>00<enter>
cout << t; // 8:10:0
38
Class scope: overloadable operators
 Binary Arithmetic: +, -, *, /, %
 Unary Arithmetic: +, -, ++, --
 Assignment: =, +=,*=, /=,-=, %=
 Bitwise: & , | , << , >> , ~ , ^
 Logical: &, | |, !
 Relational: >, < , = =, <=, >=
 De-referencing: ->
 Subscript: []
 Function call: ()
 Dynamic memory allocation: New, delete

https://www.programiz.com/cpp-programming/operator-
overloading
39
Class scope: Non-overloadable ops.
 Scope resolution (::)
 Class member access operators
 .(dot),
 .* (pointer to member operator)
 Ternary or conditional (?:)
 sizeof
 typeid

https://www.programiz.com/cpp-programming/operator-
overloading

You might also like