Master your language C++. Create portfolio projects that showcase your new skills to help land your dream job.
- Link_PDF: 300 bài code thiếu nhi.pdf
- Link Web hay: https://www.javatpoint.com/
- Link Web hay: https://viettuts.vn/
OOP is an approach to program organizational and development that attempts to eliminate some of the pitfalls of proceedural programming.
Object Oriented Programming has a capability of programming/coding (more precisely, MODELLING) any(most of) real world scenarios. Note* C++ is not purely object oriented, JAVA is a purely object oriented programming language
#include<iostream>
using namespace std;
class abc
{
int a,b;
public:
void add(int a, int b) // Inline Function -- Member function defined inside the class
{
cout<<a+b;
}
void subtract(int a, int b);
};
void abc::subtract(int a, int b) // Member function defined outside the class
{
cout<<a-b;
}
int main() {
abc x;
x.add(5,10);
x.subtract(20,10);
return 0;
}
cout
is one of the standard classes, which should be accessed be std::cout
, to ease the process of writing code we write using namespace std;
- Data Encapsulation
- Data Abstraction
- Polymorphism
- Inheritence
- Modularity
Polymorphism (Looking alike but exhibit different characteristics).In C++, polymorphism can be either
static polymorphism or
dynamic polymorphism
C++ implements static polymorphism through
overloaded functions
overloaded operators
Three ways of achieving overloading in C++
- Function Overloading
- Operator Overloading
- Dynamic Binding
A name having two or more distinct meanings
Function Overloading -- A function having two or more distinct meaning
Operator Overloading -- When two or more distinct meanings are defined for a single operator
For example -- '-' can be unary as well as binary, '*' is used for multiplication as well as pointers
Combination of function's name and its parameter types (in order). Or, a function's arguement list is known as the function's signature. Overloaded functions are distinguished by their signatures
Signature is only on the parameter's, NOT on the return type
A call to an overloaded function is resolved to a particular instance of the function, there are three possible cases, a function call may result in:
- One Match - A match is found for the function call
- No Match - No match is found for the function call
- Ambiguous Match - More than one defined instance for the function call.
For example, there are two functions with same name afunc:
void afunc(int);
void afunc(double);
The function call afunc(0);
is matched to void afunc(int); and compiler invokes corresponding function definition
as 0 (zero) is of type int
If no exact match is found, an attempt is made to achieve a match through promotion of the actual argument.
Recall that the conversion of integer types (char, short, enumerator, int) into int - integral promotion
For example, consider the following code fragment:
void afunc (int);
void afunc (float);
afunc (‘c’);
Will invoke afunc(int)
A constructor is a special member function whose task is to initialize the objects of its class. It's name is same as the name of the class.
The constructor is invoked whenever an object of it's associated class is created.
It is called constructor because it constructs the values of data members of the class.
Example
class add {
int m,n;
public:
add (void);
};
add::add(void) {
m=0;
n=0;
}
When a constructor is parametrized, we must pass the initial values as arguements to the constructor function.
A copy constructor is used
sample::sample (sample &i) {
a=i.a;
b=i.b;
}
- constructor overtloading is possible in c++.
- Default arguement constructors are allowed
A::A(int x=0)
A destructor is used to destroy the objects that have been created by a constructor Destructor never takes any arguements nor returns any value It will be invoked implicitly by the compiler upon exit from the program (or any block/function).
- Call by Value
- Call by Address
- Call ny Reerance
C++ has two new operators apart form malloc() and calloc(), called new
and delete
Similar to malloc and free in C But there is an option to initialize memory Can be used allocate memory for single or array of elements If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated. If sufficient memory is not available, the new operator returns NULL. Dynamically allocated object/array exists until the delete operator destroys it
1. Dynamic Memory Allocation 2. Dynamic Memory Allocation for Arrays 3. Dynamic Memory Allocation for Objects
Preventing program/Software to crash in case of wrong inputs by throwing appropriate error messages/.
try, catch and throw
try {
.
.
// Possibly an unexpected situation
throw(val1);
.
.
.
// Possibly an unexpected situation
throw(val2);
.
.
.
}
catch (val1) {
.. ..
.. ..
.. ..
}
catch (val2) {
.. ..
.. ..
.. ..
}
catch (...) { // catch(...) catches any throw
}
A friend function is a function that can access the non-public members of a class, even though the function itself is not a member of the class.
The concepts of encapsulation and data hiding dictate that non-member functions should not be able to access an object’s private or protected data. However, there are situations where such rigid discrimination leads to considerable inconvenience. A friend function is a normal function with special access privileges.
A friend function of a class is a non-member function of a class that has the right to access all private and protected (non-public) members of the class. Friend function prototype should be placed inside the class definition (can be any where inside the class definition). Friend function definition should be outside the class scope. Even though the prototypes of friend functions appear in the class definition, friends are not member functions.
A friend function of a class can be a
- function (non-member of a class)
- member function of another class
- function template
To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend. Friend functions are used in Operator overloading to increase the versatility of operators.
class ClassName {
// Some statements
friend returnType functionName( arguments ); // friend function declaration
// Some Statements
};
// friend function definition does not start with friend keyword
returnType functionName( arguments ) {
... ... ...
// private and protected data of the above class can be accessed from this function
... ... ...
}
int main( ) {
functionName( arguments ); // Call to the friend function
}
Member Function | Friend Functoon |
---|---|
It is invoked through an object | Not invoked through an object since it is a non-member of a class If the friend function of class X is a member function of class Y, then it must be invoked through an object of class Y |
Can access the non-public members of the class directly | Can access the non-public members of the class only through an object (since this pointer is not visible) |
Member functions of a class X operate on the data members of Class X. At times, we need a helper class to operate on non-public data members of the class X. In such circumstances, the helper class has to be treated as a friend of class X to access the non-public data members of class X. So, a class can be a friend of another class
For example:
If class Y is a friend of class X then
All the member functions of class Y can access the non-public members of class X
If class Y is a friend of class X then class X is not a friend of class Y
If class X is a friend of class Y and If class Y is a friend of class Z then class X is not a friend of class Z
class employer;// forward declaration of class Y
class employee {
... ...
friend class employer;// friend class declaration
... ...
};
class employer {
// All the member functions of class employer can access non-public members of class employee using an object
};
C++ allows most of the operators within the language to be overloaded so that they work with classes. This
- allows the language to be extended to cover new situations
- enhances program readability
- enhances program functionality
- is an essential components of C++ templates and the standard templates library
The operators . :: ?: sizeof may not be overloaded.
All other operators can be overloaded
An operator is overloaded by writing a non-static member function definition or non-member function definition as you normally would, except that the function name starts with the keyword operator followed by the symbol for the operator being overloaded.
For example, the function name operator+ would be used to overload the addition operator (+) for use with objects of a particular class.
Overloading binary addition operator
Overloading unary subtraction operator
Overloading unary increment operator
Overloading subscript operator
Inheritance means deriving qualities and characteristics from parents or ancestors.
Inheritance in Object Oriented Programming can be described as a process of creating new classes from existing classes which will have the properties similar to that of parent classes. Or simply, Inheritance is the process by which objects of one class acquire the properties of objects of another class in the hierarchy.
Subclasses provide specialized behavior from the basis of common elements provided by the super class. Through the use of inheritance, programmers can reuse the code in the super class many times.
Reusing existing code saves time and money and increases a program’s reliability.
New classes can be built from the existing classes. It means that we can add additional features to an existing class without modifying it. The new class is referred as derived class or subclass and the original class is known as base classes or super class.
class derivedClasas: accessSpecifier baseClass
Access specifiers are (as the name suggests) specifiers which tell what should be the privacy of the content, and how much content wee can access.
Access specifier can be public, protected and private. The default access specifier for data members is private. Access specifiers affect accessibility of data members of base class from the derived class. In addition, it determines the accessibility of data members of base class outside the derived class.
This inheritance mode is used mostly. In this the protected member of Base class becomes protected members of Derived class and public becomes public.
In protected mode, the public and protected members of Base class becomes protected members of Derived class.
In private mode the public and protected members of Base class become private members of Derived class.
- Single Inheritance
- Multiple Inheritance
- Multi Level Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance
One child class inherits one parent class
When one child cass inherits properties of more than one parent classes. Simply, one subclass and many super classes form a multiple inheritance.
As the name suggests, in this type of inheritance, there are multiple levels of inheritance. This is analogous to grand parents, then parents then children.
In this case the inheritance pattern forms a hierarchy, i.e., there are multiple derived classes of same base class.
Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
This is the problem arised in some cases of hybrid inheritance. In this problem a Derived class will have multiple paths to a Base class. This will result in duplicate inherited members of the Base class.
Virtual base class is used in situation where a derived have multiple copies of base class to avoid dreaded diamonds problem.
reference: http://www.tutorialdost.com/Cpp-Programming-Tutorial/51-Cpp-Virtual-Base-Class.aspx
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : public ClassA
{
public:
int b;
};
class ClassC : public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10; //Statement 1, Error occur
obj.a = 100; //Statement 2, Error occur
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
}
This will result in error Therefore, to avoid such situations, we use virtual class
#include<iostream.h>
#include<conio.h>
class ClassA
{
public:
int a;
};
class ClassB : virtual public ClassA
{
public:
int b;
};
class ClassC : virtual public ClassA
{
public:
int c;
};
class ClassD : public ClassB, public ClassC
{
public:
int d;
};
void main()
{
ClassD obj;
obj.a = 10; //Statement 1
obj.a = 100; //Statement 2
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout<< "\n A : "<< obj.a;
cout<< "\n B : "<< obj.b;
cout<< "\n C : "<< obj.c;
cout<< "\n D : "<< obj.d;
}
Output :
A : 100
B : 20
C : 30
D : 40
Here, ClassD have only one copy of ClassA and statement 4 will overwrite the value of a, given in statement 3.
There are many cases where there is a function declared in base class and then again declared in the child class, i.e., that function is overridden. So basically, a virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class.
Characteristics of virtual functions:
-
Ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
-
Used to achieve dynamic/runtime polymorphism
-
Functions are declared with a virtual keyword in base class.
-
The resolving of function call is done at Run-time.
-
They Must be declared in public section of class.
-
Virtual functions cannot be static and also cannot be a friend function of another class.
-
Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
-
The prototype of virtual functions should be same in base as well as derived class.
-
They are always defined in base class and overridden in derived class.
-
It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used.
-
A class may have virtual destructor but it cannot have a virtual constructor.
Sometimes implementation of all function cannot be provided in a base class because we don’t know the implementation. Such a class is called abstract class.
Template is a kind of macro that supports the generic programming which allows to develop the reusable components. It is one of the main features of object oriented language such as C++. Actually, it allows the declaration of data items without specifying their exact data type.
- Function Templates
- Class Templates
Function templates are generic functions, which are operating on different data items.
They describe a function format that when instantiated with particulars generates a function definition, basically it acts like a template schema which can be used
for parameters with any datatype, instead of some fixed data type
-
Avoids redifinition of function
-
Makes code more reusable (write once, use multiple times)
The C++ language allows the compiler to generate multiple versions of a function by allowing parameterized data types and hence it supports the parameterized polymorphism.
The data items (types) are not declared while defining the function.
Once when the function call is made using appropriate data type, then the template function is transformed to operate on that specific data types.
template<class type>
returntype functionname(arguments)
{
.......
statements;
.......
}
See sample program 1 here See sample program 2 here
Generic classes with template data variables and template member functions
The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL.
-
Algorithms
-
Containers
-
Functions
-
Iterators