Session1 2 3 4
Session1 2 3 4
1
► C++ is a compiled language. That means that to get a program
to run, you must first translate it from the human-readable
form to something a machine can “understand.” That
translation is done by a program called a compiler.
2
► it is important to know how to compile C++ program codes and how
to execute them. When we write code, we write it in a high-level
language that machines can't understand, known as source code.
The code that machines can understand & execute is in binary form
(0's and 1's) and is known as machine code, object code, or
executable code.
► Translating source code (high-level language code) into
machine-readable code consists of the following four processes that
we will learn in detail as we move through the course of this article:
► Pre-processing the source code
► Compiling the source code
► Assembling the compiled file
► Linking the object code file to create an executable file
3
► What is C++?
► C++ is a cross-platform language that can be used to create high-performance
applications.
► C++ was developed by Bjarne Stroustrup, as an extension to the C language.
► C++ gives programmers a high level of control over system resources and
memory.
► The language was updated 4 major times in 2011, 2014, 2017, and 2020 to
C++11, C++14, C++17, C++20.
4
► Difference between C and C++
► C++ was developed as an extension of C, and both languages have almost the
same syntax.
► The main difference between C and C++ is that C++ support classes and
objects, while C does not.
5
► To start using C++, you need two things:
► A text editor, like Notepad, to write C++ code
► A compiler, like GCC, to translate the C++ code into a language that the
computer will understand
6
► C++ Install IDE
► An IDE (Integrated Development Environment) is used to edit AND compile the
code.
► Popular IDE's include Code::Blocks, Eclipse, and Visual Studio. These are all
free, and they can be used to both edit and debug C++ code.
► Note: Web-based IDE's can work as well, but functionality is limited.
► Download the mingw-setup.exe file, which will install the text editor
with a compiler.
7
create our first C++ file.
Open Codeblocks and go to File > New > Empty File.
Write the following C++ code and save the file
as myfirstprogram.cpp (File > Save File as):
8
► #include <iostream>
using namespace std;
int main()
► {
cout << "Hello World!";
return 0;
}
► Line 1: #include <iostream> is a header file library that lets us work
with input and output objects, such as cout (used in line 5). Header files
add functionality to C++ programs
► Line 2: using namespace std means that we can use names for objects
and variables from the standard library.
9
Line 3: A blank line. C++ ignores white space. But we use it to make the code more
readable.
Line 4: Another thing that always appear in a C++ program, is int main(). This is
called a function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion
operator (<<) to output/print text. In our example it will output "Hello World!".
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the
code more readable.
Line 7: Do not forget to add the closing curly bracket } to actually end the main
function
10
Omitting Namespace
► You might see some C++ programs that runs without the standard
namespace library. The using namespace std line can be omitted and
replaced with the std keyword, followed by the :: operator for some
objects:
► #include <iostream>
int main() {
std::cout << "Hello World!";
return 0;
}
int main() {
cout << "Hello World!";
cout << "I am dancing";
return 0;
}
► Note: The symbol << is called insertion operation and output operator.
► The insertion operator << is the one we usually use for output, as in:
► cout << "This is output" << end;
► It gets its name from the idea of inserting data into the output stream.
► >> Operator called extraction operator. The extraction operator (>>), which is preprogrammed for
13
all standard C++ data types, is the easiest way to get bytes from an input stream object.
New Lines
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
► #include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
15
Both \n and endl are used to break lines. However, \n is
most used.
But what is \n exactly?
The newline character (\n) is called an escape
sequence,
and it forces the cursor to change its position to the
beginning of the next line on the screen. This results in
a new line.
16
Escape sequence Character represented
\b Backspace
\n New-line
\r Carriage return
\t Horizontal tab
\v Vertical tab
\? Question mark
17
\\ Backslash
C++ Comments
► Comments can be used to explain C++ code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.
Comments can be singled-lined or multi-lined.
► Single-line comments start with two forward slashes (//).
► // This is a comment
cout << "Hello World!";
► ---------------------
► /* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";
18
C++ Variables
► imagine that I ask you to remember the number 5, and then I ask you to also memorize the number
2 at the same time.
► You have just stored two different values in your memory (5 and 2).
► Now, if I ask you to add 1 to the first number I said, you should be retaining the numbers 6 (that is
5+1) and 2 in your memory.
► Then we could, for example, subtract these values and obtain 4 as result.
► The whole process described above is a simile of what a computer can do with two variables. The
same process can be expressed in C++ with the following set of statements:
a = 5;
b = 2;
a = a + 1;
result = a - b;
19
► We can now define variable as a portion of memory to store a value.
► Each variable needs a name that identifies it and distinguishes it from the
others.
► For example, in the previous code the variable names were a, b, and result, but we could
have called the variables any names we could have come up with, as long as
they were valid C++ identifiers.
20
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with
different keywords), for example:
•int - stores integers (whole numbers), without decimals,
such as 123 or -123
► Example
► int myNum;
myNum = 15;
cout << myNum;
22
Note that if you assign a new value to an
existing variable, it will overwrite the
previous value:
► int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
cout << myNum; // Outputs 10
23
Basic Data Types
24
e.g.s
► int myNum = 1000;
cout << myNum;
► ---------------------------------------
► float myNum = 5.75;
cout << myNum;
► --------------------
► double myNum = 19.99;
cout << myNum;
► ------------------------
► Note:
float vs. double
The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only six
25
26
C++ Boolean Data Types
A boolean data type is declared with the bool keyword and can
only take the values true or false.
When the value is returned, true = 1 and false = 0.
27
C++ Character Data Types
28
C++ String Data Types
The string type is used to store a sequence of characters (text).
`This is not a built-in type, but it behaves like one in its most basic
String values must be surrounded by double quotes:
string greeting = "Hello";
cout << greeting;
To use strings,
you must include an additional header file in the source code,
the <string> library:
// Include the string library
#include <string>
► int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
30
Create a variable named gg and assign the value 3567to
31
C++ Declare Multiple Variables
32
Identifiers
► All C++ variables must be identified with unique names.
► These unique names are called identifiers.
► . That means that an identifier written in capital letters is not equivalent to another
one with the same name but written in small letters. T
► hus, for example, the RESULT variable is not the same as the result variable or
the Result variable. These are three different identifiers identifiying three different
variables.
34
The general rules for naming variables
are:or variable naming convension
The general rules for naming variables are:
•Names are case sensitive (myVar and myvar are different variables)
•Reserved words (like C++ keywords, such as int) cannot be used as names
35
C++ Constants
use the const keyword (this will declare
the variable as "constant", which
means unchangeable and
read-only):
► const int myNum = 15; // myNum will always be
15
myNum = 10; // error: assignment of read-only
variable 'myNum'
36
Important note
► When you declare a constant variable, it must be assigned
with a value:
► Literals
► Literals are the most obvious kind of constants. They are used to express
particular values within the source code of a program.
These literal constants have a type, just like variables. By default, integer literals are of type
int. However, certain suffixes may be appended to an integer literal to specify a different integer type:
Unsigned may be combined with any of the other two in any order to form unsigned long or unsigned long long.
Suffix Type modifier
u or U unsigned
l or L long
ll or LL long long 37
Preprocessor definitions (#define)
40
Ans is …
Note that
the #define lines are preprocessor directives,
and as such are single-line instructions that -unlike C++
statements-
x = 5; y = 2 + x;
x = y = z = 5; is this valid ?
44
Arithmetic operators ( +, -, *, /, % )
operator description
+ addition
- subtraction
* multiplication
/ division
% modulo
45
Operations of addition, subtraction, multiplication and division
correspond literally to their respective mathematical operators.
The last one, modulo operator, represented by a percentage
sign
(%), gives the remainder of a division of two values. For
example:
x = 11 % 3;
results in variable x containing the value 2, since dividing 11 by 3 results in 3, with
a remainder of 2.
46
Compound assignment (+=, -=, *=, /=, %=,
>>=, <<=, &=, ^=, |=)
47
1
2
// compound assignment operators
3 #include <iostream>
4
5 using namespace std;
6
7
int main ()
8 {
9
10 int a, b=3; a = b;
11 a+=2; // equivalent to a=a+2
cout << a;
Return 0;
}
48
Increment and decrement (++, --)
some expression can be shortened
even more: the increase operator
(++) and the decrease operator (--)
increase or reduce by one the value
stored in a variable. They are
equivalent to +=1 and to -=1,
respectively. 1 ++x;
2 x+=1;
Thus:
3 x=x+1; 49
Relational and comparison operators ( ==,
!=, >, <, >=, <= )
operator description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
(7 == 5) // evaluates to false
(5 > 4) // evaluates to true
(3 != 2) // evaluates to true
(6 >= 6) // evaluates to true 50
,
.
51
Conditional ternary operator ( ? :)
52
Comma operator ( , )
The comma operator (,) is used to separate
two or more expressions that are
included where only one expression is
expected. When the set of expressions
has to be evaluated for a value, only the
right-most expression is considered.
1 a = (b=3, b+2); 53
Bitwise operators ( &, |, ^, ~, <<, >> )
operator asm equivalent description
& AND Bitwise AND
Bitwise inclusive
| OR
OR
Bitwise exclusive
^ XOR
OR
Unary
~ NOT complement (bit
inversion)
<< SHL Shift bits left 54
i = int (f);
55
sizeof
56
Basic Input/Output
1 cout << "First sentence." << endl;
2 cout << "Second sentence." << endl;
int age;
cin >> age;
57
58
Statements and flow control
► Selection statements: if (x == 100)
cout << "x is 100";
► if (condition) statement
64
65
The do-while loop
► Do
► statement
► ……..
► …..
► while (condition);
► It behaves like a while-loop,
► For example, the following example program echoes any text the user introduces
until the user enters goodbye:
►
66
do {
// code block to be executed
}
while (condition);
► int i = 0;
► do {
► cout << i << "\n";
► i++;
► }
► while (i < 5);
67
68
The for loop
69
Continued…
Like the while-loop, this loop repeats statement while condition is true.
But, in addition, the for loop provides specific locations to contain an initialization and
an increase expression, executed before the loop begins the first time, and
after each iteration, respectively.
Therefore, it is especially useful to use counter variables as condition.
1.initialization is executed. Generally, this declares a counter variable, and sets it to some initial value.
2. This is executed a single time, at the beginning of the loop.
2.condition is checked. If it is true, the loop continues; otherwise, the loop ends, and
3. statement is skipped, going directly to step 5.
3.statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces { }.
4.increase is executed, and the loop gets back to step 2.
5.the loop ends: execution continues by the next statement after it.
70
eg
return 0;
#include <iostream>
using namespace std;
intThe
mainbreak
() statement
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
} } }
72
The continue statement
► The continue statement causes the program to skip the rest of
the loop in the current iteration, as if the end of the statement
block had been reached, causing it to jump to the start of the
following iteration. For example, let's skip number 5 in our
countdown:
► // continue loop example
► #include <iostream>
► using namespace std;
► int main ()
► {
► for (int n=10; n>0; n--) {
► if (n==5) continue;
► cout << n << ", ";
► }
► cout << "liftoff!\n"; 73
► }
The goto statement
► goto allows to make an absolute jump to another point in the
program. This unconditional jump ignores nesting levels, and does not
cause any automatic stack unwinding. Therefore, it is a feature to use
with care, and preferably within the same block of statements,
especially in the presence of local variables.
► int main ()
► {
► int n=10;
► mylabel:
► cout << n << ", ";
► n--;
► if (n>0) goto mylabel;
► cout << "liftoff!\n";
► }
75
Another selection statement: switch.
► The syntax of the switch statement is a bit peculiar. Its purpose is to check for a value among a
number of possible constant expressions. It is something similar to concatenating if-else
statements, but limited to constant expressions. Its most typical syntax is:
► code>switch (expression)
► {
► case constant1:
► group-of-statements-1;
► break;
► case constant2:
► group-of-statements-2;
► break;
► default:
► default-group-of-statements
► }/code>
76
► This is how it works:
77
► int day = 4;
► switch (day) {
► case 1:
► cout << "Monday";
► break;
► case 2:
► cout << "Tuesday";
► break;
► case 3:
► cout << "Wednesday";
► break;
► case 4:
► cout << "Thursday";
► break;
► case 5:
► cout << "Friday";
► break;
► case 6:
► cout << "Saturday";
► break;
► case 7:
► cout << "Sunday";
► break;
78
► }
► // Outputs "Thursday" (day 4)
The default Keyword
The default keyword specifies some code to run if
there is no case match:
► int day = 4;
► switch (day) {
► case 6:
► cout << "Today is Saturday";
► break;
► case 7:
► cout << "Today is Sunday";
► break;
► default:
► cout << "Looking forward to the Weekend";
► }
79
Arrays
► To declare an array, define the variable type, specify the name of the array
followed by square brackets and specify the number of elements it should
store:
80
► string cars[4];
► string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
► int myNum[3] = {10, 20, 30};
► Access the Elements of an Array
► string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
► cout << cars[0];
► // Outputs Volvo
81
Functions
► Functions are used to perform certain actions, and they are important for
reusing code: Define the code once, and use it many times.
► void myFunction() {
► // code to be executed
► }
82
► // Create a function
► void myFunction() {
► cout << "I just got executed!";
► }
► int main() {
► myFunction(); // call the function
► return 0;
► }
83
► A function can be called multiple times:
► void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
84
► Function Declaration and Definition
► A C++ function consist of two parts:
► Declaration: the return type, the name of the function, and parameters (if
any)
► Definition: the body of the function (code to be executed)
► void myFunction() { // declaration
// the body of the function (definition)
}
85
► int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
86
► However, it is possible to separate the declaration and the definition of the
function - for code optimization.
► You will often see C++ programs that have function declaration above main(),
and function definition below main(). This will make the code better
organized and easier to read:
87
► // Function declaration
► void myFunction();
► // Function definition
► void myFunction() {
► cout << "I just got executed!";
► }
88
C++ Function Parameters
► Parameters are specified after the function name, inside the parentheses.
You can add as many parameters as you want, just separate them with a
comma:
89
► Syntax
► void functionName(parameter1, parameter2, parameter3) {
► // code to be executed
► }
► The following example has a function that takes a string called fname as parameter.
When the function is called, we pass along a first name, which is used inside the
function to print the full name:
► void myFunction(string fname) {
► cout << fname << " Refsnes\n";
► }
► int main() {
► myFunction(“anju");
► myFunction(“manju");
► myFunction("Anu");
► return 0;
► } 90
The Return Keyword / call by value
► Return Values
► The void keyword, used in the previous examples, indicates that the function should not
return a value. If you want the function to return a value, you can use a data type (such as
int, string, etc.) instead of void, and use the return keyword inside the function:
► `int myFunction(int x) {
► return 5 + x;
► }
► int main() {
► cout << myFunction(3);
► return 0;
► }
91
92
Functions - Pass By Reference
► Pass By Reference
► void swapNums(int &x, int &y) {
► int z = x;
► x = y;
► y = z;
► }
► int main() {
► int firstNum = 10;
► int secondNum = 20;
► cout << "Before swap: " << "\n";
► cout << firstNum << secondNum << "\n";
► // Call the function, which will change the values of firstNum and secondNum
► swapNums(firstNum, secondNum);
93
► return 0;
► }
Function Overloading
With function overloading, multiple functions can have the same name with different
parameters : ► int myFunction(int x)
► float myFunction(float x)
► double myFunction(double x, double y)
► Example
► int plusFuncInt(int x, int y) {
► return x + y;
► }
► }
OOP
► OOP stands for Object-Oriented Programming.
95
► C++ What are Classes and Objects?
► Classes and objects are the two main aspects of object-oriented
programming.
► Look at the following illustration to see the difference between class and
objects:
96
97
Classes/Objects
► Everything in C++ is associated with classes and objects, along
with its attributes and methods. For example: in real life, a
car is an object. The car has attributes, such as weight and
color, and methods, such as drive and brake.
99
Create an Object
► To create an object of MyClass, specify the class name, followed by the object name.
► To access the class attributes (myNum and myString), use the dot syntax (.) on the
object:
► class MyClass { // The class
► public: // Access specifier
► int myNum; // Attribute (int variable)
► string myString; // Attribute (string variable)
► };
► int main() {
► MyClass myObj; // Create an object of MyClass
► // Access attributes and set values
► myObj.myNum = 15;
► myObj.myString = "Some text";
► // Print attribute values
► cout << myObj.myNum << "\n";
► cout << myObj.myString;
► return 0; 100
► }
Multiple Objects you can create multiple objects of one class:
► // Create a Car class with some attributes
► class Car {
► public:
► string brand;
► string model;
► int year; };
► int main() {
► // Create an object of Car
► Car carObj1;
► carObj1.brand = "BMW";
► carObj1.model = "X5";
► carObj1.year = 1999;
► // Create another object of Car
► Car carObj2;
► carObj2.brand = "Ford";
► carObj2.model = "Mustang";
► carObj2.year = 1969;
► // Print attribute values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
101
► return 0;
► }
Class Methods
► Methods are functions that belongs to the class.
102
► class MyClass { // The class
► public: // Access specifier
► void myMethod() { // Method/function defined inside the class
► cout << "Hello World!";
► }
► };
► int main() {
► MyClass myObj; // Create an object of MyClass
► myObj.myMethod(); // Call the method
► return 0;
► }
103
Usage of :: or
► To define a function outside the class definition,
you have to declare it inside the class and then
define it outside of the class.
► This is done by specifiying the name of the class,
followed the scope resolution :: operator,
followed by the name of the function:
104
eg
► class MyClass { // The class
► public: // Access specifier
► void myMethod(); // Method/function declaration
► };
► int main() {
► MyClass myObj; // Create an object of MyClass
► myObj.myMethod(); // Call the method
► return 0; 105
► }
Parameters You can also add parameters:
► #include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
106
Difference between Structure and Class in
C++
► In C++, the structure is the same as the class with some differences. Security
is the most important thing for both structure and class. A structure is not
safe because it could not hide its implementation details from the end-user,
whereas a class is secure as it may hide its programming and design details
107
► A structure is a grouping of variables of various data types referenced by the same name. A
structure declaration serves as a template for creating an instance of the structure.
► Syntax:
► Struct Structurename
► {
► Struct_member1;
► Struct_member2;
► Struct_member3;
► .
► .
► .
► Struct_memberN;
► };
108
► A class in C++ is similar to a C structure in that it consists of a list of data members and a
set of operations performed on the class. In other words, a class is the building block of
Object-Oriented programming. It is a user-defined object type with its own set of data
members and member functions that can be accessed and used by creating a class instance.
A C++ class is similar to an object's blueprint.
► Syntax:
► class class_name
► {
► // private data members and member functions.
► Access specifier;
► Data member;
► Member functions (member list){ . . }
► };
109
Main differences between the structure and
class
► By default, all the members of the structure are public. In contrast, all members of
the class are private.
► The structure will automatically initialize its members. In contrast, constructors and
destructors are used to initialize the class members.
► When a structure is implemented, memory allocates on a stack. In contrast, memory
is allocated on the heap in class.
► Variables in a structure cannot be initialized during the declaration, but they can be
done in a class.
► There can be no null values in any structure member. On the other hand, the class
variables may have null values.
► A structure is a value type, while a class is a reference type.
► Operators to work on the new data form can be described using a special method.
110
Features Structure Class
Definition A structure is a grouping of variables of In C++, a class is defined as a collection of
various data types referenced by the same related variables and functions contained within
name. a single structure.
Basic If no access specifier is specified, all If no access specifier is defined, all members
members are set to 'public'. are set to 'private'.
Declaration struct structure_name{ type struct_member class class_name{ data member; member
1; type struct_member 2; type struct_member function; };
3; . type struct_memberN; };
Instance Structure instance is called the 'structure A class instance is called 'object'.
variable'.
Inheritance It does not support inheritance. It supports inheritance.
Usage It is used for smaller amounts of data. It is used for a huge amount of data.
Requires It may have only parameterized constructor. It may have all the types of constructors and
► Similarities
► The following are similarities between the structure and class:
► Both class and structure may declare any of their members private.
► Both class and structure support inheritance mechanisms.
► Both class and structure are syntactically identical in C++.
► A class's or structure's name may be used as a stand-alone type.
112
container class…
► A container class is a data type that is capable of holding a collection of items. In C++, container
classes can be implemented as a class, along with member functions to add, remove, and examine
items.
► As an example, I have two classes A and B. An object of B is a member of class A (container). What
is the best way to access data of container class (A) from the member class (object of B).
Also, I don't want to use inheritance (B -> A) as B is not logically derived from A.
113
► class first {
► public:
► void showf()
► { cout << "Hello from first class\n";
► } };
► // Container class
► class second {
► // creating object of first
► first f;
► public:
► // constructor
► second() {
► // calling function of first class
► f.showf();
► } };
► int main() {
► // creating object of second
114
► second s; }
115
Constructors
116
eg
► class MyClass { // The class
► public: // Access specifier
► MyClass() { // Constructor
► cout << "Hello World!";
► }
► };
► int main() {
► MyClass myObj; // Create an object of MyClass (this
will call the constructor)
► return 0;
► } 117
Constructor Parameters or parameterized constructor
► Constructors can also take parameters (just like regular functions), which can be useful for setting initial values for attributes.
► class Car { // The class
► public: // Access specifier
► string brand; // Attribute
► string model; // Attribute
► int year; // Attribute
► Car(string x, string y, int z) { // Constructor with parameters
► brand = x;
► model = y;
► year = z;
► }
► };
► int main() {
► // Create Car objects and call the constructor with different values
► Car carObj1("BMW", "X5", 1999);
► Car carObj2("Ford", "Mustang", 1969);
► // Print values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
118
► return 0;
► }
Just like functions, constructors can also be defined outside the class. First, declare
the constructor inside the class, and then define it outside of the class by specifying
the name of the class, followed by the scope resolution ::
► class Car { // The class
► };
► brand = x;
► model = y;
► year = z;
► }
► int main() {
► // Create Car objects and call the constructor with different values
► // Print values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
► return 0;
► } 119
► class Car { // The class
► public: // Access specifier
► string brand; // Attribute
► string model; // Attribute
► int year; // Attribute
► Car(string x, string y, int z); // Constructor declaration
► };
► int main() {
► // Create Car objects and call the constructor with different values
► Car carObj1("BMW", "X5", 1999);
► Car carObj2("Ford", "Mustang", 1969);
► // Print values
► cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
► cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
120
► return 0;
► }
Access Specifiers
121
► In C++, there are three access specifiers:
122
Example
► class MyClass {
► public: // Public access specifier
► int x; // Public attribute
► private: // Private access specifier
► int y; // Private attribute
► };
► int main() {
► MyClass myObj;
► myObj.x = 25; // Allowed (public)
► myObj.y = 50; // Not allowed (private)
► return 0;
► }
►
123
Execute this and tell me the result
► If you try to access a private member, an error occurs:
► error: y is private
► Note: It is possible to access private members of a class using a public method
inside the same class. See the next chapter (Encapsulation) on how to do this.
► Note: By default, all members of a class are private if you don't specify an
access specifier:
124
Encapsulation
► The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve
this, you must declare class variables/attributes as private (cannot be accessed from outside the class).
If you want others to read or modify the value of a private member, you can provide public get and set
methods.
► Access Private Members
► To access a private attribute, use public "get" and "set" methods:
► #include <iostream>
using namespace std;
class Employee {
private: // Private attribute
int salary;
public: // Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000); 125
cout << myObj.getSalary();
return 0;
} same prg in next slide
► #include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000); 126
cout << myObj.getSalary();
return 0;
Encapsulation?
127
Syllabus
128
Inheritance
► The mechanism of deriving a new class from an existing class is called inheritance.
► The existing class is referred as base class and the new one is called derived class.
► The derived class inherits all capabilities of base class & also add new features to this class. But the base
class remains unchanged
► this feature supports code reusability.
► Once a class has been written and tested , it can be used by other programmers to suit their requirements.
► In C++, it is possible to inherit attributes and methods from one class to another. We group the "inheritance
concept" into two categories:
► derived class (child) - the class that inherits from another class
► base class (parent) - the class being inherited from
► To inherit from a class, use the : symbol.
129
► Defining Derived Classes :
►
130
eg. for single inheritance :
► #include<iostream.h>
► #include<conio.h>
► class emp
► {
► int no;
► char name[10];
► public:
► void get( )
► {
► cout<< "\n\nenter no & name \n";
► cin>>no;
► cin >>name;
► }
► void print( )
► {
► cout<<"\n\nname is "<< name;
► cout<<"\nno is " << no;
► } 131
► };
► class physic : public emp
► {
► float height,weight;
► public:
► void read( )
► { get( ) ;
► cin >> height >> weight; }
► void disp()
► {
► print();
► cout<<height;
► cout<<weight;}
132
► };
Continued……
► void main( )
► {
► physic p;
► clrscr();
► p.read();
► p.disp();
► getch();
► } 133
► Visibility Modes
►
► void put()
► { cout << no;}
► };
►
136
Cont..
► class der : public bas
► {
► char name[10];
► public :
► void get()
► { cin >> name;}
► void put()
► {cout<<"\n name = "<<name ; }
};
137
Cont..
► void main()
► { der d;
► d.bas::get();
► d.get();
► d.bas::put();
► d.put();
► }
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
► https://cplusplus.com/doc/tutorial/variables/
► https://www.javatpoint.com/cpp-variable
156