Programming in C++
Programming in C++
Presented by:
Ms. Smita Rani Biswal
1.1
Object oriented programming is a type of programming which uses objects and classes
its functioning.
The object oriented programming is based on real world entities like inheritance,
polymorphism, data hiding, etc.
It aims at binding together data and function work on these data sets into a single
entity to restrict their usage.
Concepts of OOP
A class is a data-type that has its own members i.e. data members and member
functions.
It is the blueprint for an object in object oriented programming language.
It is the basic building block of object oriented programming in C++.
The members of a class are accessed in programming language by creating an instance
of the class.
Properties of Class
Data Hiding:
Data hiding is a technique of hiding internal object
details, i.e., data members.
It is an object-oriented programming technique.
Data hiding ensures, or we can say guarantees to
restrict the data access to class members. It maintains
data integrity.
Data Hiding cont.…
Data hiding means hiding the internal data within the class to
prevent its direct access from outside the class.
What is message?
A request for an object to perform one of its operations is called a message.
Operation means method/function.
A message cannot go automatically it creates an interface, which means it
creates an interface for an object.
The interface provides the abstraction over the message means hide the
implementation. So we get to know,
An interface is a set of operations that a given object can perform.
All communication between objects is done via message is called message passing
To make possible message passing the following things have to be followed
to be done :
•We have to create classes that define objects and its behavior.
•Then Creating the objects from class definitions
•Calling and connecting the communication among objects
1.2
#include <iostream>
int main()
{
cout << "Hello World!";
return 0;
}
New Lines
Example
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Another way to insert new line is, with endl manipulator.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
Tokens in C++ (Keywords, Identifiers, Constants,
Strings, Operators, Special Symbols )
Tokens act as building blocks of a program. Just like a living cell is the
smallest possible unit of life, tokens in C++ are referred to as the smallest
individual units in a program.
C++ Keywords
C++ allows the programmer to assign names of his own choice to variables,
arrays, functions, structures, classes, and various other data structures called
identifiers.
The programmer may use the mixture of different types of character sets
available in C++ to name an identifier.
Rules for C++ Identifiers
First character
No special characters
No keywords
No white spaces
Word limit
Case sensitive
C++ Constants
Syntax:
const data_type variable_name = value;
C++ Strings
Just like characters, strings in C++ are used to store letters and digits.
Strings can be referred to as an array of characters as well as an individual
data type.
It is enclosed within double quotes, unlike characters which are stored within
single quotes. The termination of a string in C++ is represented by the null
character, that is, ‘\0’. The size of a string is the number of individual
characters it has.
char name[30] = ‘’Hello!”;
char name[30] = { ‘H’ , ’e’ , ’l’ , ’l’ , ’o’};
Special Symbols
{}
{}
,
#
*
`
.
C++ Operators
Operators are tools or symbols which are used to perform a specific operation
on data. Operations are performed on operands.
Operators can be classified into three broad categories according to the number
of operands used.
Types:
Unary
Binary
Operator types:
• Arithmetic
• Relational
• Logical
• Assignment
• Bitwise
• Conditional
C++ Variables
In C++, there are different types of variables (defined with
different keywords), for example:
#include <iostream>
using namespace std;
int main() {
int myNum = 215;
cout << myNum;
return 0;
}
Other Types
int myNum = 5; // Integer (whole number
without decimals)
double myFloatNum = 5.99; // Floating point
number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or
false)
Display Variables
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
C++ Declare Multiple Variables
int x = 5, y = 6, z = 50;
cout << x + y + z;
C++ User Input
We have already learned that cout is used to
output (print) values. Now we will use cin to get
user input.
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
Example:
#include <iostream>
using namespace std;
int main() {
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
return 0;
}
Data types:
A data type determines the type and the operations that can be performed on
the data.
C++ provides various data types and each data type is represented differently
within the computer’s memory.
The various data types provided by C++ are built-in data types, derived data
types and user-defined data types as shown in Figure.
Example
#include <iostream>
#include <string>
using namespace std;
int main () {
// Creating variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myString = "Hello"; // String
Basic Data Types
Data Type Size Description
return 0;
}
C++ Operators
#include <iostream>
using namespace std;
int main() {
int x = 100 + 50;
cout << x;
return 0;
}
Example
#include <iostream>
using namespace std;
int main() {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
cout << sum1 << "\n";
cout << sum2 << "\n";
cout << sum3;
return 0;
}
Types
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic Operators
#include <iostream>
using namespace std;
int main() {
int x = 10;
x += 5;
cout << x;
return 0;
}
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
int main() {
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
return 0;
}
perator Name Example
== Equal to x == y
!= Not equal x != y
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}
String Concatenation
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
C++ Numbers and Strings
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string x = "10";
string y = "20";
string z = x + y;
cout << z;
return 0;
}
C++ String Length
string txt = "We are the so-called "Vikings" from the north.";
\\ \ Backslash
C++ User Input Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
C++ Math
#include <cmath>
int x = 10;
int y = 9;
cout << (x > y);
C++ If ... Else
The if Statement
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
Example
#include <iostream>
using namespace std;
int main() {
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
return 0;
}
C++ Else
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
C++ Else If
The else if Statement
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
#include <iostream>
using namespace std;
int main() {
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
return 0;
}
C++ Switch Statements
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
.
.
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
C++ While Loop
#include <iostream>
using namespace std;
int main() {
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
return 0;
}
C++ Do/While Loop
#include <iostream>
using namespace std;
int main() {
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
return 0;
}
C++ For Loop
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
return 0;
}
C++ Break and Continue
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
return 0;
}
C++ Continue
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
return 0;
}
C++ Arrays
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
return 0;
}
C++ Arrays and Loops
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
return 0;
}
C++ Omit Array Size
#include <iostream>
#include <string>
using namespace std;
int main() {
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
for(int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
return 0;
C++ Array Size
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
C++ Functions
Syntax
void myFunction()
{
// code to be executed
}
Call a Function
#include <iostream>
using namespace std;
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
A function can be called multiple times:
void myFunction() {
cout << "I need to be executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Function Declaration and Definition
#include <iostream>
using namespace std;
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Function Parameters
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
C++ Default Parameters
Default Parameter Value
#include <iostream>
#include <string>
using namespace std;
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
Multiple Parameters
#include <iostream>
#include <string>
using namespace std;
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Return Values
The void keyword, used in the previous
examples, indicates that the function
should not return a value.
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
This example returns the sum of a function with two parameters:
#include <iostream>
using namespace std;
int main() {
cout << myFunction(5, 3);
return 0;
}
Pass By Reference
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);
return 0;
C++ Pass Array to a Function
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Function Overloading
int plusFunc(int x, int y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Recursion
int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
int main() {
int result = sum(10);
cout << result;
return 0;
C++ Classes and Objects
C++ is an object-oriented programming language.
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.
Attributes and methods are basically variables and functions that
belongs to the class. These are often referred to as "class members".
A class is a user-defined data type that we can use in our program,
and it works as an object constructor, or a "blueprint" for creating
objects.
UNIT-2
Class Structure
3. Member classes/structures of a
class are private by default but not 3. Member classes/structures of a
all programming languages have structure are public by default.
this default behavior eg Java etc.
Structure vs Class Cont…
6. NULL values are possible in Class. 6. NULL values are not possible.
7. Syntax: 7. Syntax:
class class_name{ struct structure_name{
data_member; type structure_member1;
member_function; type structure_member2;
}; };
Create a Class
class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
#include <iostream>
#include <string>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
// Print values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
C++ Class Methods
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
Outside Example
#include <iostream>
using namespace std;
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
Member Function
It has access to all the members of the class and can operate on
any object of that class.
Example
class Dice {
public:
double L; // a dice's length
double B; // a dice's breadth
double H; // a dice's height
double getVolume (void); // Returns dice volume
};
Inline Member function
class Dice {
public:
double L; // a dice's length
double B; // a dice's breadth
double H; // a dice's height
double getVolume(void) {
return L * B * H;
}
};
Outside class
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 (x is public)
myObj.y = 50; // Not allowed (y is private)
return 0;
#include <iostream>
using namespace std;
class Room
{
public:
double length; double breadth; double height;
double calculateArea ()
{ return length * breadth;
}
double calculateVolume ()
{
return length * breadth * height;
}
};
int main()
{ // create object of Room class Room room1; // assign values to data members
room1.length = 42.5; room1.breadth = 30.8; room1.height = 19.2; // calculate
and display the area and volume of the room cout << "Area of Room = " <<
room1.calculateArea() << endl; cout << "Volume of Room = " <<
Inline Function in C++
Syntax:
Inline returnType function_name (parameters)
{
code
}
Example
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
// Main function for the program int main()
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) <<
endl;
return 0; }
Static Data Members in C++
Static data members are class members that are declared using the static keyword.
There is only one copy of the static data member in the class, even if there are many
class objects.
This is because all the objects share the static data member.
The static data member is always initialized to zero when the first class object is
created.
To create Static data member
Syntax:
Static data_type datamember_name;
Example:
#include <iostream>
#include<string.h>
using namespace std;
class Student
{
private: int rollNo; char name[10]; int marks;
public: static int objectCount;
Student()
{
objectCount++;
}
void getdata()
{ cout << "Enter roll number: "<<endl;
cin >> rollNo;
cout << "Enter name: "<<endl;
cin >> name;
cout << "Enter marks: "<<endl;
cin >> marks;
Cont..
void putdata()
{
cout<<"Roll Number = "<< rollNo <<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;
cout<<endl;
} };
int Student::objectCount = 0;
int main(void)
{
Student s1;
s1.getdata();
s1.putdata();
Student s2;
s2.getdata();
s2.putdata();
Student s3; s3.getdata(); s3.putdata(); cout << "Total objects
created = " << Student::objectCount << endl; return 0; }
Static Function Members
A friend function in C++ is defined as a function that can access private, protected, and
public members of a class.
Syntax
class className {
... .. ...
friend returnType
functionName(arguments);
... .. ...
}
We declare a friend function inside the body of a class, whose private and protective
data needs to be accessed, starting with the keyword friend to access the data.
We use them when we need to operate between two different classes at the same time.
What is Friend Function?
Friend functions of the class are granted permission to access private and protected
members of the class in C++.
They are defined globally outside the class scope.
Friend functions are not member functions of the class. So, what exactly is the friend
function?
A friend function in C++ is a function that is declared outside a class but is capable of
accessing the private and protected members of the class.
There could be situations in programming wherein we want two classes to share their
members.
These members may be data members, class functions or function templates.
In such cases, we make the desired function, a friend to both these classes which will
allow accessing private and protected data of members of the class.
Generally, non-member functions cannot access the private members of a particular
class. Once declared as a friend function, the function is able to access the private and
protected members of these classes.
User-defined Function types
class class_name
{
friend data_type function_name(arguments/s); //syntax of friend function.
};
In the above declaration, the keyword friend precedes the function. We can define the
friend function anywhere in the program like a normal C++ function. A class’s function
definition does not use either the keyword friend or scope resolution operator :: .
Friend function is called as function_name(class_name) and member function is called
as class_name. function_name.
Characteristics of a Friend function:
• The function is not in the scope of the class to which it has been declared as a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
• It can be declared either in the private or the public part.
#include <iostream>
using namespace std;
class B; // forward declarartion.
class A
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(A,B); // friend function.
};
class B
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(A,B); // friend function
};
void min(A a,B b)
{
if(a.x<=b.y)
std::cout << a.x << std::endl;
else
std::cout << b.y << std::endl;
}
int main()
{
A a;
B b;
1. a.setdata(10);
2. b.setdata(20);
3. min(a,b);
4. return 0;
Example
#include <iostream>
using namespace std;
class Test
{
private:
int x;
protected:
int y;
public:
int z;
friend void Fun();
void Fun()
{
Test t;
t.x = 10;
t.y = 20;
t.z = 30;
cout << " X : " << t.x << endl;
cout << " Y : " << t.y << endl;
cout << " Z : " << t.z << endl;
}
int main()
{
Fun();
return 0;
}
Output
X=10
Y=20
Z=30
Characteristics of a Friend Function in C++:
1. The function is not in the scope of the class to which it has been declared as a
friend.
2. It cannot be called using the object as it is not in the scope of that class.
3. It can be invoked like a normal function without using the object.
4. It cannot access the member names directly and has to use an object name
and dot membership operator with the member’s name.
5. It can be declared either in the private or the public part.
A friend function of a class is defined outside that class scope but it has the
right to access all private, protected, and public members of the class.
Even though the prototypes for friend functions appear in the class definition,
friends are not member functions.
C++ Friend class
A friend class can access both private and protected members of the class in which it
has been declared as friend.
#include <iostream>
class A
{
int x =5;
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
int main()
{
A a;
B b;
b.display(a);
return 0;
}
#include <iostream>
using namespace std;
class GFG {
private:
int private_variable;
protected:
int protected_variable;
public:
GFG()
{
private_variable = 10;
protected_variable = 99;
}
public:
void display(GFG& t)
{
cout << "The value of Private Variable = "
<< t.private_variable << endl;
cout << "The value of Protected Variable = "
<< t.protected_variable;
}
};
// Driver code
int main()
{
GFG g;
F fri;
fri.display(g);
return 0;