Abstraction 1
Abstraction 1
Table of
Abstraction
Contents
02 “Virtual” keyword
03 Virtual function
05 Abstract class
06
Interface
Abstraction
1 What is “Abstraction” ?
2 When is “Abstraction” used ?
Code reusability
Improves maintainability
01 02 03
04 02
int main()
{
Account *ptr1 = new Checking;
PS D:\C++ (OOP)> ./test ptr1->withdraw();
Checking::withdraw
return 0;
}
Rules of virtual function
No.3 Access through object pointers Can be friend of another class No.4
Rules of virtual function
Understand the concept
Instance Context Vtable concept Polymorphism
Object context Vtable and Vptr Runtime Polymorphism
class Account
{
protected:
int data1; int main()
public: {
void withdraw() Account *ptr1 = new Checking;
{
std::cout << "Account::withdraw"
ptr1->withdraw();
<< this->data1;
} return 0;
}; }
class Checking: public Account
{
private:
int data2;
public:
void withdraw()
{
std::cout << "Checking::withdraw"
<< this->data1;
<< this->data2;
}
};
Rules of virtual function
Explanation
Members of some classes Object-Oriented Design
Why 1
Defined in base class, even though not use virtual table integrity
Why 5
Avoid overloaded
Why 6 Base and derived virtual functions must match
Why 2 – Cannot be the static member
class Base {
public:
virtual void show() { // Hàm ảo
std::cout << "Base class show function\n";
}
static void staticShow() { // Hàm tĩnh
std::cout << "Base class static show function\n";
}
};
int main() {
Base* b = new Derived();
b->show(); // Gọi hàm show() của lớp Derived
class AnotherClass {
private:
int privateData;
public:
AnotherClass(int value) : privateData(value) {}
friend class Derived;
};
01 02 03
return 0; return 0;
} }
Pure virtual function
1 2 3 4
No Class
Similar with
definition in contains it Define in
virtual
base class. becomes derived class
function
Assign to 0 abstract class
Abstract class
1 2 3 4
Include at
Cannot be Base class
least 1 Intended for
initialized on for other
pure virtual Inheritance
its own classes
function
Implementation
class Account //Abstract class
{
public:
//Pure virtual function
virtual void withdraw() = 0;
};
1 2 3 4
Contain no
All member member Doesn’t have
Pure abstract
functions are variables and any
class implemented
pure constructor
methods
Implementation
//Pure abstract class
class Shape
{
public:
//Pure virtual functions
virtual void draw() = 0;
virtual void rotate() = 0;
};
Concept of interface