You are on page 1of 149

Programming in C++

Presented by:
Ms. Smita Rani Biswal
1.1

Introduction to Object Oriented


Programming
Object Oriented Programming

 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

 Some basic concepts of object oriented programming are −


• CLASS
• OBJECTS
• ENCAPSULATION
• POLYMORPHISM
• INHERITANCE
• ABSTRACTION
Class

 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

• Class is a user-defined data-type.


• A class contains members like data members and member functions.
• Data members are variables of the class.
• Member functions are the methods that are used to manipulate data members.
• Data members define the properties of the class whereas the member functions define
the behavior of the class.
 A class can have multiple objects which have properties and behaviour that in common
for all of them.
 Syntax:
 Class class_name
 {
 Data_type data_name;
 Return_type
 }
OOPs Concepts

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.

 Data encapsulation hides the private methods and class data


parts, whereas Data hiding only hides class data components.
Both data hiding and data encapsulation are essential concepts of
object-oriented programming.

 Encapsulation wraps up the complex data to present a simpler


view to the user, whereas Data hiding restricts the data use to
assure data security.
 Data hiding also helps to reduce the system complexity
to increase the robustness by limiting the
interdependencies between software components.

 Data hiding is achieved by using the private access


specifier.
Example:
 Account class with data member balance

 by declaring the balance attribute private, we can restrict the


access to balance from an outside application.

 Access specifiers define how the member's functions and


variables can be accessed from outside the class. So, there are
three access specifiers available within a class that are stated as
follows:
Private members/methods:

 Functions and variables declared as private can be


accessed only within the same class, and they cannot be
accessed outside the class they are declared.
Public members/methods:

 Functionsand variables declared under public


can be accessed from anywhere.
Protected members/methods:

 Functions and variables declared as protected cannot be


accessed outside the class except a child class.

 This specifier is generally used in inheritance.


Message Passing

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

Getting started with C++


Basic Syntax:

 #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

 Keywords in C++ refer to the pre-existing, reserved words, each holding


its own position and power and has a specific function associated with it.

alignas alignof asm auto bool break


case catch char char16_t char32_t class
const_cas
const constexpr continue decltype default
t
dynamic_
delete double do else enum
cast
explicit export extern FALSE float for
C++ Identifiers

 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

 constants are referred to as fixed values that cannot


change their value during the entire program run as soon
as we define them.

 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:

•int - stores integers (whole numbers), without decimals,


such as 123 or -123

•double - stores floating point numbers, with decimals, such


as 19.99 or -19.99

•char - stores single characters, such as 'a' or 'B'. Char values


are surrounded by single quotes

•string - stores text, such as "Hello World". String values are


surrounded by double quotes

•bool - stores values with two states: true or false


Declaring (Creating) Variables

type variableName = value;


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 myAge = 35;


cout << "I am " << myAge << " years old.";
Add Variables Together

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.

cin is a predefined variable that reads data from


the keyboard with the extraction operator (>>).

In the following example, the user can input a


number, which is stored in the variable x. Then we
print the value of x:
Example

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

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII


values

int 2 or 4 Stores whole numbers, without decimals


bytes

float 4 bytes Stores fractional numbers, containing one or more


decimals. Sufficient for storing 6-7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more


decimals. Sufficient for storing 15 decimal digits
// Print variable values
cout << "int: " << myNum << "\n";
cout << "float: " << myFloatNum << "\n";
cout << "double: " << myDoubleNum << "\n";
cout << "char: " << myLetter << "\n";
cout << "bool: " << myBoolean << "\n";
cout << "string: " << myString << "\n";

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

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x


C++ Assignment Operators
 The addition assignment operator += adds a value to a operator.

#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

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


C++ Comparison Operators
#include <iostream>
using namespace std;

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

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


C++ Logical Operators

Operator Name Description Example


&& Logical Returns true if both x < 5 && x < 10
and statements are true
|| Logical or Returns true if one of the x < 5 || x < 4
statements is true
! Logical Reverse the result, returns !(x < 5 && x <
not false if the result is true 10)
C++ Strings

#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 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


cout << "The length of the txt string is: " << txt.length();
Access Strings

 string myString = "Hello";


cout << myString[0];
Strings - Special Characters

 string txt = "We are the so-called "Vikings" from the north.";

Escape character Result Description

\' ' Single quote

\" " Double quote

\\ \ 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

Max and min


cout << max(5, 10);
C++ <cmath> Header

#include <cmath>

cout << sqrt(64);


cout << round(2.6);
cout << log(2);
Function Description

abs(x) Returns the absolute value of x

acos(x) Returns the arccosine of x

asin(x) Returns the arcsine of x

atan(x) Returns the arctangent of x

cbrt(x) Returns the cube root of x

ceil(x) Returns the value of x rounded up to its nearest integer

cos(x) Returns the cosine of


C++ Booleans

bool isCodingFun = true;


bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
Boolean Expression

 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

 int myNumbers[5] = {10, 20, 30, 40, 50};


cout << sizeof(myNumbers);
Scope resolution operator in C++

#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

 A function is a block of code which only runs when it is called.


 You can pass data, known as parameters, into a function.
 Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Create a Function

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

 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)
}
However, it is possible to separate the declaration and the definition of
the function - for code optimization.

#include <iostream>
using namespace std;

// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Function Parameters

Parameters and Arguments


Information can be passed to functions as a parameter. Parameters act
as variables inside the function.
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:
void functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
#include <iostream>
#include <string>
using namespace std;

void myFunction(string fname) {


cout << fname << " Refsnes\n";
}

int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
C++ Default Parameters
Default Parameter Value
#include <iostream>
#include <string>
using namespace std;

void myFunction(string country = "Norway") {


cout << country << "\n";
}

int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
Multiple Parameters
#include <iostream>
#include <string>
using namespace std;

void myFunction(string fname, int age) {


cout << fname << " Refsnes. " << age << " years old. \n";
}

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.

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:
#include <iostream>
using namespace std;

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 myFunction(int x, int y) {


return x + y;
}

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;

cout << "Before swap: " << "\n";


cout << firstNum << secondNum << "\n";

// Call the function, which will change the values of firstNum and
secondNum
swapNums(firstNum, secondNum);

cout << "After swap: " << "\n";


cout << firstNum << secondNum << "\n";

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;
}

double plusFunc(double x, double 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

 Recursion is the technique of making a function call itself. This


technique provides a way to break complicated problems down into
simple problems which are easier to solve.
Example
#include <iostream>
using namespace std;

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 and Object


Structure vs Class

Class Structure

1. Members of a class are private 1. Members of a structure are


by default. public by default.

2. An instance of a class is called 2. An instance of structure is called


an ‘object’. the ‘structure variable’.

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…

4. It is declared using 4. It is declared using


the class keyword. the struct keyword.

5. It is normally used for data 5. It is normally used for the grouping


abstraction and further inheritance. of data

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

 To create a class use Class keyword.

 class MyClass
 { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
#include <iostream>
#include <string>
using namespace std;

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 values
cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
C++ Class Methods

 Methods are functions that belongs to the class.


 here are two ways to define functions that belongs to a class:
• Inside class definition
• Outside class definition
Inside Example
#include <iostream>
using namespace std;

class MyClass { // The class


public: // Access specifier
void myMethod() { // Method/function
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
Outside Example
#include <iostream>
using namespace std;

class MyClass { // The class


public: // Access specifier
void myMethod(); // Method/function declaration
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
Member Function

 A class member function is a function that, like any other


variable, is defined or prototyped within the class declaration.

 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

double Dice::getVolume (void) {


return L * B * H;
}
Access Specifiers
In C++, there are three access specifiers:

•public - members are accessible from outside the class

•private - members cannot be accessed (or viewed) from


outside the class

•protected - members cannot be accessed from outside the


class, however, they can be accessed in inherited classes. You
will learn more about Inheritance later.
#include <iostream>
using namespace std;

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++

 In C++, we can declare a function as inline.


 This copies the function to the location of the function call in compile-time and may
make the program execution faster.
To create Inline Function

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

 By declaring a function member as static, you make it independent of any particular


object of the class.
 A static member function can be called even if no objects of the class exist and
the static functions are accessed using only the class name and the scope resolution
operator ::.
 A static member function can only access static data member, other static member
functions and any other functions from outside the class.
 Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to determine
whether some objects of the class have been created or not.
Example
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
Box(double l = 2.0, double b = 2.0, double h = 2.0)
{ cout <<"Constructor called." << endl;
length = l; breadth = b; height = h; // Increase every time object is created objectCount++; }
double Volume() { return length * breadth * height; }
static int getCount()
{
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
{
// Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
// Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
return 0;
}
Friend Function in C++?

 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

• Function with no argument and no return value


• Function with no argument but with return value
• Function with argument but no return value
• Function with argument and return value
Declaration of a friend function in C++

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>

using namespace std;

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;
}

// friend class declaration


friend class F;
};
{
class F

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;

You might also like