0% found this document useful (0 votes)
13 views92 pages

C

C++ is a versatile programming language that supports procedural, object-oriented, and generic programming, making it a middle-level language. It includes key concepts such as classes, objects, methods, variable scope, functions, arrays, and pointers, which are essential for building structured and efficient programs. The document provides examples of syntax and usage for various C++ features, including variable declaration, function definition, and array manipulation.

Uploaded by

quansaha085
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views92 pages

C

C++ is a versatile programming language that supports procedural, object-oriented, and generic programming, making it a middle-level language. It includes key concepts such as classes, objects, methods, variable scope, functions, arrays, and pointers, which are essential for building structured and efficient programs. The document provides examples of syntax and usage for various C++ features, including variable declaration, function definition, and array manipulation.

Uploaded by

quansaha085
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

C++

OVERVIEW

C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that
supports procedural, object-oriented, and generic programming.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level
language features.
Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-oriented development

• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
BASIC SYNTAX
When we consider a C++ program, it can be defined as a collection of objects that communicate via invoking
each other's methods. Let us now briefly look into what a class, object, methods, and instant variables mean.
• Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors - wagging, barking, eating. An object is an instance of a class.
• Class − A class can be defined as a template/blueprint that describes the behaviors/states that object of its
type support.
• Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the
logics are written, data is manipulated and all the actions are executed.
• Instance Variables − Each object has its unique set of instance variables. An object's state is created by the
values assigned to these instance variables.
#include <iostream>
using namespace std;

// main() is where program execution begins.


int main() {
cout << "Hello World"; // prints Hello World
return 0;
}
Let us look at the various parts of the above program −
• The C++ language defines several headers, which contain information that is either necessary or useful to
your program. For this program, the header <iostream> is needed.
• The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively
recent addition to C++.
• The next line '// main() is where program execution begins.' is a single-line comment available in C++.
Single-line comments begin with // and stop at the end of the line.
• The line int main() is the main function where program execution begins.
• The next line cout << "This is my first C++ program."; causes the message "This is my first C++ program" to
be displayed on the screen.
• The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.
VARIABLE SCOPE

A scope is a region of the program and broadly speaking there are three places, where variables can be
declared −
• Inside a function or a block which is called local variables,
• In the definition of function parameters which is called formal parameters.
• Outside of all functions which is called global variables.
• Local Variables
Variables that are declared inside a function or block are local variables. They can be used only by statements
that are inside that function or block of code. Local variables are not known to functions outside their own.
EXAMPLE
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
GLOBAL VARIABLES

Global variables are defined outside of all the functions, usually on top of the program. The global variables
will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout
your entire program after its declaration.
EXAMPLE
#include <iostream>
using namespace std;
// Global variable declaration:
int g;

int main () {
// Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
A program can have same name for local and global variables but value of local variable inside a function will
take preference. Example:

#include <iostream>
using namespace std;
// Global variable declaration:
int g = 20;
int main () {
// Local variable declaration:
int g = 10;
cout << g;
return 0;
}
CONSTANT/LITERALS

Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating-Point
Numerals, Characters, Strings and Boolean Values.
Defining Constants
There are two simple ways in C++ to define constants −
• Using #define preprocessor.
• Using const keyword.
THE #DEFINE PREPROCESSOR
#define identifier value
#include <iostream>
using namespace std;

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}
THE CONST KEYWORD

const type variable = value;


#include <iostream>
using namespace std;

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


cout << area;
cout << NEWLINE;
return 0;
}
FUNCTIONS

• A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main(), and all the most trivial programs can define additional functions.
• You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division usually is such that each function performs a specific task.
• A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function.
DEFINING A FUNCTION
return_type function_name( parameter list ) {
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a function

• Return Type − A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
• Function Name − This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
• Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type,
order, and number of the parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
• Function Body − The function body contains a collection of statements that define what the function does.
EXAMPLE
• Following is the source code for a function called max(). This function takes two parameters num1 and
num2 and returns the maximum between the two
// function returning the max between two numbers

int max(int num1, int num2) {


// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
CALLING A FUNCTION

• While creating a C++ function, you give a definition of what the function has to do. To use a function, you
will have to call or invoke that function.
• When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when it’s return statement is executed or when its function-ending closing brace
is reached, it returns program control back to the main program.
• To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value
EXAMPLE
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int ret;

// calling a function to get max value.


ret = max(a, b);
cout << "Max value is : " << ret << endl;

return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
DEFAULT VALUES FOR PARAMETERS

• When you define a function, you can specify a default value for each of the last parameters. This value
will be used if the corresponding argument is left blank when calling to the function.
• This is done by using the assignment operator and assigning values for the arguments in the function
definition. If a value for that parameter is not passed when the function is called, the default given value
is used, but if a value is specified, this default value is ignored and the passed value is used instead
EXAMPLE
#include <iostream>
using namespace std;
int sum(int a, int b = 20) {
int result;
result = a + b;
return (result);
}
int main () {
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the values.

result = sum(a, b);


cout << "Total value is :" << result << endl;
// calling a function again as follows.

result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
ARRAYS

An array is used to store a collection of data, but it is often more useful to think of an array as a collection
of variables of the same type.
All arrays consist of memory locations. The lowest address corresponds to the first element and the highest
address to the last element.
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the elements and the number of elements
required by the array.
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type
can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use
this statement
double balance[10];
Initializing Arrays
You can initialize C++ array elements either one by one or using a single statement as follows
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we declare for
the array between square brackets [ ]. Following is an example to assign a single element of the array
If you omit the size of the array, an array just big enough to hold the initialization is created
EXMAPLE 1
#include <iostream>
using namespace std;

int foo[] = {16,2,77,45,12071,5};


int n, result = 0;

int main(int argc, char** argv) {


for (n = 0; n<5; ++n)
{
result += foo[n];
}
cout << result;
return 0;
}
EXAMPLE 2
#include <iostream>

using namespace std;

int main() {
int numbers[5], sum = 0;
cout<<"Enter 5 numbers: ";

for(int i = 0; i < 5; ++i)


{
cin >> numbers[i];
sum += numbers[i];
}
cout << "Sum = " << sum << endl;
return 0;
}
TWO DIMENSIONAL ARRAY
C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration
type name[size1][size2]...[sizeN];
example
#include <iostream>
using namespace std;
int main () {
// an array with 5 rows and 2 columns.

int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};


// output each array element's value

for ( int i = 0; i < 5; i++ )


for ( int j = 0; j < 2; j++ ) {
cout << "a[" << i << "][" << j << "]: ";
cout << a[i][j]<< endl;
}
return 0;
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
float a[2][2], b[2][2], c[2][2];
int i, j;
// Taking input using nested for loop
cout<<"Enter elements of 1st matrix\n";
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
cout<<"Enter : ", i+1, j+1;
cin>>a[i][j];
}
// Taking input using nested for loop

cout<<"Enter elements of 2nd matrix\n";


for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
cout<<"Enter: ", i+1, j+1;
cin>>b[i][j];
}
0 1 2 3

1 1 2 3
// adding corresponding elements of two arrays
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
c[i][j] = a[i][j] + b[i][j];
}
// Displaying the sum
cout<<"Sum Of Matrix:\n";
for(i=0; i<2; ++i)
for(j=0; j<2; ++j)
{
cout<<c[i][j];
if(j==1)
cout<<"\n";
}
return 0;
}
3-DIMENSIONAL ARRAYS
#include <iostream>
using namespace std;
int main() {
int test[2][3][2];
cout<<"Enter 12 values: \n";
for (int i = 0; i<2; ++i)
{
for(int j = 0; j<3; ++j)
{
for(int k = 0; k<2; ++k)
{

cin>>test[i][j][k];
}
}
}
cout<<"\n Displaying values stored: "<<endl;
for (int i = 0; i<2; ++i)
{
for(int j = 0; j<3; ++j)
{
for(int k = 0; k<2; ++k)
{

cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i][j][k] <<endl;


}
}
}
return 0;
}
PASSING ARRAY-FUNCTION

If you want to pass a single-dimension array as an argument in a function, you would have to declare function
formal parameter in one of following three ways and all three declaration methods produce similar results
because each tells the compiler that an integer pointer is going to be received.
• Way-1
Formal parameters as a pointer as follows:
void myFunction(int *param) {
.
.
.
}
• Way 2
Formal parameters as a sized array as follows:
void myFunction(int param[10]) {
.
.
}

• Way 3
Formal parameters as an unsized array as follows:
void myFunction(int param[]) {
.
.
.
}
Now, consider the following function, which will take an array as an argument along with another argument
and based on the passed arguments, it will return average of the numbers passed through the array :
double getAverage(int arr[], int size) {
int i, sum = 0;
double avg;

for (i = 0; i < size; ++i) {


sum += arr[i];
}
avg = double(sum) / size;

return avg;
}
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int arr[], int size);
int main () {
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
// output the returned value
cout << "Average value is: " << avg << endl;
return 0;
}
POINTERS

A pointer is a variable whose value is the address of another variable. Like any variable or constant, you
must declare a pointer before you can work with it. The general form of a pointer variable declaration is
type *var-name;
type is the pointer's base type; it must be a valid C++ type and var-name is the name of the pointer
variable. The asterisk you used to declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a variable as a pointer. Following are the
valid pointer declaration
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a
long hexadecimal number that represents a memory address. The only difference between pointers of different
data types is the data type of the variable or constant that the pointer points to.
USING POINTERS

There are few important operations, which we will do with the pointers very frequently.
(a) We define a pointer variable.
(b) Assign the address of a variable to a pointer.
(c) Finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at the address
specified by its operand
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl;
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl;
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
POINTERS - ARRAY

An array name is a constant pointer to the first element of the array.


Therefore, in the declaration:
double balance[50];
balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the
following program fragment assigns p the address of the first element of balance
double *p;
double balance[10];

p = balance;
It is legal to use array names as constant pointers, and vice versa. Therefore, *(balance + 4) is a legitimate
way of accessing the data at balance[4].
Once you store the address of first element in p, you can access array elements using *p, *(p+1), *(p+2)
and so on. Below is the example to show all the concepts discussed above
#include <iostream>
using namespace std;
int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;

// output each array element's value


cout << "Array values using pointer " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
cout << "Array values using balance as address " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
}
return 0;
In the above example, p is a pointer to double which means it can store address of a variable of double type.
Once we have address in p, then *p will give us value available at the address stored in p
NULL POINTERS
It is always a good practice to assign the pointer NULL to a pointer variable in case you do not have exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called
a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries, including iostream.

#include <iostream>

using namespace std;


int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;

return 0;
}
POINTER ARITHMETIC

As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic
operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used
on pointers: ++, --, +, and –
Incrementing a Pointer
Using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the
array name which cannot be incremented because it is a constant pointer. The following program increments
the variable pointer to access each succeeding element of the array
#include <iostream>
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have array address in pointer.
ptr = var;
for (int i = 0; i < MAX; i++) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;

// point to the next location


ptr++;
}
return 0;
DECREMENTING A POINTER
#include <iostream>
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the last element in pointer.
ptr = &var[MAX-1];
for (int i = MAX; i > 0; i--) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr--;
}
return 0;
}
POINTER COMPARISONS

Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
The following program modifies the previous example one by incrementing the variable pointer so long as
the address to which it points is either less than or equal to the address of the last element of the array,
which is &var[MAX - 1]
#include <iostream>
using namespace std;
const int MAX = 3;
int main () {
int var[MAX] = {10, 100, 200};
int *ptr;
// let us have address of the first element in pointer.
ptr = var;
int i = 0;
while ( ptr <= &var[MAX - 1] ) {
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the previous location
ptr++;
i++; }
return 0;
POINTERS TO POINTERS

A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains
the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of
the second pointer, which points to the location that contains the actual value
pointer pointer variable
ADDRESS ADDRESS VALUE
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional
asterisk in front of its name. For example, following is the declaration to declare a pointer to a pointer of
type int
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the
asterisk operator be applied twice.
#include <iostream>
using namespace std;
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
// take the address of var
ptr = &var;

// take the address of ptr using address of operator &


pptr = &ptr;

// take the value using pptr


cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;

return 0;
PASSING POINTERS TO FUNCTIONS

C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer
type

The function which can accept a pointer, can also accept an array-
As shown in the example below:
#include <iostream>
using namespace std;
// function declaration:
double getAverage(int *arr, int size);
int main () {

// an int array with 5 elements.


int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.


avg = getAverage( balance, 5 ) ;

// output the returned value


cout << "Average value is: " << avg << endl;
return 0;
}
double getAverage(int *arr, int size) {
int i, sum = 0;
double avg;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = double(sum) / size;
return avg;
OBJECT-ORIENTED PROGRAMMING

C++ supports object-oriented (OO) style of programming which allows you to divide complex problems into
smaller sets by creating objects.
Object is simply a collection of data and functions that act on those data.

C++ Class
A class is a blueprint for the object.
We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors,
windows etc. Based on these descriptions we build the house. House is the object.
As, many houses can be made from the same description, we can create many objects from a class.
HOW TO DEFINE A CLASS

A class is defined in C++ using keyword class followed by the name of class.
The body of class is defined inside the curly brackets and terminated by a semicolon at the end.

class className
{
// some data
// some functions
};
EXAMPLE
class Test
{
private:
int data1;
float data2;

public:
void function1()
{ data1 = 2; }

float function2()
{
data2 = 3.5;
return data2;
}
};
The private keyword makes data and functions private. Private data and functions can be accessed only
from inside the same class.

The public keyword makes data and functions public. Public data and functions can be accessed out of the
class.
CREATING OBJECTS

When class is defined, only the specification for the object is defined; no memory or storage is allocated.
To use the data and access functions defined in the class, you need to create objects.
EXAMPLE
class Test{
private:
int data1;
float data2;
public:
void function1()
{ data1 = 2; }

float function2()
{
data2 = 3.5;
return data2;
}
};
int main()
{
Test o1, o2;
EXAMPLE CLASSES AND OBJECTS
#include <iostream>
using namespace std;

class Test
{
private:
int data1;
float data2;

public:

void insertIntegerData(int d)
{
data1 = d;
cout << "Number: " << data1;
}

float insertFloatData()
{
cout << "\nEnter data: ";
cin >> data2;
return data2;
}
};
ACCESSING DATA MEMBERS
The public data members of objects of a class can be accessed using the direct member access operator (.)
Example
#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
OVERLOADING

C++ allows you to specify more than one definition for a function name or an operator in the same scope,
which is called function overloading and operator overloading respectively.
You can have multiple definitions for the same function name in the same scope. The definition of the
function must differ from each other by the types and/or the number of arguments in the argument list.
You cannot overload function declarations that differ only by return type.
EXAMPLE
#include <iostream>
using namespace std;

class printData{
public:
void print(int i){
cout<<"printing int: " << i <<endl;
}
void print(double f){
cout<<"printing flaot: " << f << endl;
}
void print(char* c){
cout<<"printing character: "<< c <<endl;
}
};
int main() {
printData pd;

pd.print(5);

pd.print(500.263);

pd.print("how are you?");


return 0;
}
CONSTRUCTORS

A constructor is a special type of member function that initializes an object automatically when it is
created.
Compiler identifies a given member function is a constructor by its name and the return type.
Constructor has the same name as that of the class and it does not have any return type. Also, the
constructor is always public.
... .. ...
class temporary
{
private:
int x;
float y;
public:
// Constructor
temporary(): x(5), y(5.5)
{
// Body of constructor
}
... .. ...
};
int main()
{
Temporary t1;
... .. ...
}
USE OF CONSTRUCTOR

Suppose you are working on 100's of Person objects and the default value of a data member age is 0.
Initialising all objects manually will be a very tedious task.
Instead, you can define a constructor that initialises age to 0. Then, all you have to do is create a Person
object and the constructor will automatically initialise the age.
These situations arise frequently while handling array of objects.
Also, if you want to execute some code immediately after an object is created, you can place the code
inside the body of the constructor.
EXAMPLE
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
// Constructor
Area(): length(5), breadth(2){ }

void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
int AreaCalculation() { return (length * breadth); }
void DisplayArea(int temp)
{
cout << "Area: " << temp;
}
};
int main()
{
Area A1, A2;
int temp;
A1.GetLength();
temp = A1.AreaCalculation();
A1.DisplayArea(temp);
cout << endl << "Default Area when value is not taken from user" << endl;
temp = A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
CONSTRUCTOR OVERLOADING

Constructor can be overloaded in a similar way as function overloading


Overloaded constructors have the same name (name of the class) but different number of arguments.
Depending upon the number and type of arguments passed, specific constructor is called.
Since, there are multiple constructors present, argument to the constructor should also be passed while
creating an object.
EXAMPLE
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
// Constructor with no arguments
Area(): length(5), breadth(2) { }

// Constructor with two arguments


Area(int l, int b): length(l), breadth(b){ }
void GetLength()
{
cout << "Enter length and breadth respectively: ";
cin >> length >> breadth;
}
void DisplayArea(int temp)
{
cout << "Area: " << temp << endl;
}
};
int main()
{
Area A1, A2(2, 1);
int temp;

cout << "Default Area when no argument is passed." << endl;


temp = A1.AreaCalculation();
A1.DisplayArea(temp);

cout << "Area when (2,1) is passed as argument." << endl;


temp = A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
INHERITANCE

Inheritance is one of the key features of Object-oriented programming in C++. It allows user to create a new
class (derived class) from an existing class(base class).
The derived class inherits all the features from the base class and can have additional features of its own.

Suppose, in your game, you want three characters - a maths teacher, a footballer and a businessman.
Since, all of the characters are persons, they can walk and talk. However, they also have some special skills. A
maths teacher can teach maths, a footballer can play football and a businessman can run a business.
Talk() Talk() Talk()
You can individually create three classes who can walk, talk and perform their special skill
Walk() Walk() Walk()
TeachMaths()
Maths Teacher Footballer
PlayFootball() Business Man RunBusiness()
If you want to add a new feature - eat, you need to implement the same code for each character. This can easily
become error prone (when copying) and duplicate codes.

It'd be a lot easier if we had a Person class with basic features like talk, walk, eat, sleep, and add special skills to
those features as per our characters. This is done using inheritance.
PERSON
Talk()
Walk()
Eat()

TeachMath() PlayFootball() RunBusiness()

Maths Teacher Footballer Business Man


Using inheritance, now you don't implement the same code for walk and talk for each class. You just need to
inherit them.
So, for Maths teacher (derived class), you inherit all features of a Person (base class) and add a new feature
TeachMaths. Likewise, for a footballer, you inherit all the features of a Person and add a new feature
PlayFootball and so on.
This makes your code cleaner, understandable and extendable.
It is important to remember: When working with inheritance, each derived class should satisfy the condition
whether it "is a" base class or not. In the example above, Maths teacher is a Person, Footballer is a Person. You
cannot have: Businessman is a Business.
IMPLEMENTING INHERITANCE
class Person
{
... .. ...
};

class MathsTeacher : public Person


{
... .. ...
};

class Footballer : public Person


{
.... .. ...
};
EXAMPLE
#include <iostream>
using namespace std;
class Person
{
public:
string profession;
int age;
Person(): profession("unemployed"), age(16) { }
void display()
{
cout << "My profession is: " << profession << endl;
cout << "My age is: " << age << endl;
walk();
talk();
}
void walk() { cout << "I can walk." << endl; }
void talk() { cout << "I can talk." << endl; }
};
CONT…..

// MathsTeacher class is derived from base class Person.


class MathsTeacher : public Person
{
public:
void teachMaths() { cout << "I can teach Maths." << endl; }
};

// Footballer class is derived from base class Person.


class Footballer : public Person
{
public:
void playFootball() { cout << "I can play Football." << endl; }
};
CONT….
int main()
{
MathsTeacher teacher;
teacher.profession = "Teacher";
teacher.age = 23;
teacher.display();
teacher.teachMaths();

Footballer footballer;
footballer.profession = "Footballer";
footballer.age = 19;
footballer.display();
footballer.playFootball();

return 0;
ENCAPSULATION

All C++ programs are composed of the following two fundamental elements −
• Program statements (code) − This is the part of a program that performs actions and they are called functions.
• Program data − The data is the information of the program which gets affected by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that
manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to
the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them and data
abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the
user.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined types,
called classes. We already have studied that a class can contain private, protected and public members. By
default, all items defined in a class are private.
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}

private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The variables length, breadth, and height are private. This means that they can be accessed only by other
members of the Box class, and not by any other part of your program. This is one way encapsulation is
achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare them after the
public keyword. All variables or functions defined after the public specifier are accessible by all other functions
in your program.
Making one class a friend of another exposes the implementation details and reduces encapsulation. The ideal
is to keep as many of the details of each class hidden from all other classes as possible.
EXAMPLE
#include <iostream>
using namespace std;
class Adder {
public:
// constructor
Adder(int i = 0) {
total = i;
}
// interface to outside world
void addNum(int number) {
total += number;
}
// interface to outside world
int getTotal() {
return total;
};
CONT….
private:
// hidden data from outside world
int total;
};
int main() {
Adder a;

a.addNum(10);
a.addNum(20);
a.addNum(30);

cout << "Total " << a.getTotal() <<endl;


return 0;
}

You might also like