Sunteți pe pagina 1din 30

C++ documentation

First CPP program:


#include <iostream> // Pre-processor Directive , input file
using namespace std; // Standard Library
int main() // Every computer program starts with a main function. It
understands where the program is started.
{
cout << "Hello world!" << endl; //cout is output stream statement. It makes the line output
on the screen.
return 0; // It makes sure that program is compiled successfully.
}
Printing statements on the Screen:
1) On same line: When we don’t use “endl” or “\n”, the statements are continued in
same line.
#include <iostream>

using namespace std;

int main()
{
cout << "Hello world!";
cout << "Sarang";
return 0;
}
Output : Hello world! Sarang

2) On next line : Using endl or \n..


#include <iostream>

using namespace std;

int main()
{
cout << "Hello world!"<<endl; or cout<< ”Hello world! \n”;
cout << "Sarang";
return 0;
}
Output : Hello world!
Sarang

3) Adding Blank Spaces :


#include <iostream>

using namespace std;

int main()
{
cout << "Hello world! \n\n";
cout << "Sarang";
return 0;
}
Output : Hello world!

Sarang

4) Each Word on new line :


#include <iostream>

using namespace std;

int main()
{
cout << "Hello \n world! \n Sarang \n Ghode \n";
return 0;
}
Output : Hello
world!
Sarang
Ghode
Variables: It’s basically a placeholder for values. (Data type) (Variable Name).
Eg. int x = 5;

#include <iostream>

using namespace std;

int main()
{
int x = 6;
int y = 8;
int prod = x*y ;
cout<< "product is:"<<prod ;
}
Output : product is:48

Basic Calculator:
#include <iostream>

using namespace std;

int main()
{
int a; // Declaring the variables
int b;
int sum, sub, prod;
float div;
cout<<"Enter the first number \n";
cin>> a; // “cin” : input stream, to take input from user.
cout<<"Enter the second number \n";
cin>> b;
sum = a+b;
cout <<"Sum is "<<sum<<endl;
sub = a-b;
cout<<"Sub is "<<sub<<endl;
prod = a*b;
cout<<"Product is "<<prod<<endl;
div = a/b;
cout<<"Div is "<<div<<endl;
return 0;
}
Overwriting the variables: C++ stores the numbers at particular memory location. So
when you assign a new value to the variable, it overwrites the old one.

#include <iostream>
Using namespace std;
int main()
{
int x = 87;
x = 78;
cout<<”Number is “;
}
Output: 78

Precedence of Operators :
() : Parenthesis First.
*, / : Multiplication or division.
+,- : Addition or subtraction

Relational Operators:
< , > , >=, <=
Equality Operators:
== : equals something. != : Not equals something.

If statement :
If (Test){
Body
}
#include <iostream>
using namespace std;
int main(){
int a;
int b;
cout<<"Enter the two numbers \n";
cin>>a>>b;
if (a>b)
{
cout<<"Executed"; // if condition is true.
}
return 0;
}
Functions :
a) No parameter :
Return_type function_name(){
Body;
}

#include <iostream>
Using namespace std;
int main(){
print();
return 0;
}
void print(){
cout<<”HII”<<endl;
}
Output : Error. Because the compiler follow top down approach. Since main program is
written first, it doesn’t know about the print function.

#include <iostream>
Using namespace std;
void print(){
cout<<”HII”<<endl;
}
int main(){
print();
return 0;
}
Output : HII.

Function Prototyping: Writing the function name before main, so that the compiler
remembers it.
#include <iostream>
Using namespace std;
void print(); //Function Prototype.
int main(){
print();
return 0;
}
void print(){
cout<<”HII”<<endl;
}
Output: HII

b) Single Parameters: function_type name (Parameter)


#include <iostream>
using namespace std;
void print(int x){
cout<<”Number is”<<x<<endl;
}
int main(){
print(8);
return 0;
}
Output : Number is 8

c) Multiple Parameters:
#include <iostream>
using namespace std;
int add(int a, int b, int c,int d) \\ Multiple parameters.
{
int sum = a+b*c+d;
return sum;
}
int main(){
cout<<add(50,60,70,89);
return 0;
}
Output : 4369.

Classes and Objects :


Classes are defined to take functions together.
class class_name
{
Body;
};
Objects: To access the stuff inside the class.
Class_name object_name;
#include <iostream>
using namespace std;
class A{ \\ Declaring class.
public :
void print(){
cout<<"Sarang Ghode";
}
};
int main()
{
A obj; \\ Declaring object.
obj.print();
return 0;
}
Classes with variables :
#include <iostream>
#include<string>
using namespace std;
class A{
public:
string name; \\ variable is declared public. NEVER DO THIS.
};

int main(){
A obj;
obj.name ="Sarang";
cout<<obj.name;
return 0;
}

Correct method : Accessing private variables by public functions.


#include <iostream>
#include <string>
Using namespace std;
Class A{
private :
string name;

public :
void setName(string x){
name = x;
}
string getName(){
return name;
}
};

int main(){
A obj;
obj.setName(“Sarang Ghode”);
cout<<obj.getName();
return 0;
}
Constructors : A special function which is called as soon as object is created. It is useful
when we have a bunch of variables in a class and we need to initially set them values.

#include <iostream>
#include<string>
using namespace std;
class A{

public :
A(string a){ \\ Constructor declared
setName(a);
}
void setName(string x){
name = x;
}
string getName(){
return name;
}

private:
string name;
};

int main(){
A obj("Sarang Ghode"); \\ Parameter passed.
cout<<obj.getName();
return 0;
}
Output : Sarang Ghode

Nested if else statement:


#include <iostream>

using namespace std;

int main()
{
int x,y;
cout<<"Enter the two numbers \n";
cin>>x>>y;
if(x>y)
{
if(x%2==0)
{
cout<<x<<" is divisible by 2"<<endl;
}
}
else{
cout<<x<<" is smaller than "<<y<<endl;
}
return 0;
}
Output : Enter two numbers
18
9
18 is divisible by 2.

While loop : entry level loop. Checks the condition while entering the loop.
#include <iostream>
using namespace std;

int main()
{
int a = 0;
while(a<=5){ \\ Condition of a while loop.
cout<<"Sarang "<<a<<endl;
a = a+1; \\ Terminating condition
}
return 0;
}
Output: Sarang 0
Sarang 1
Sarang 2
…..
Sarang 5

Program: To get sum of 5 numbers using while loop.


#include <iostream>
using namespace std;
int main()
{
int a,b,c,d,e;
cout<<"Enter the 5 numbers "<<endl;
cin>>a>>b>>c>>d>>e;
int sum = 0;
while(sum==0){
sum = sum + a;
sum = sum + b;
sum = sum + c;
sum = sum + d;
sum = sum + e;
cout <<"Sum is "<<sum;
}
return 0;
}

OR
#include <iostream>
using namespace std;
int main()
{
int x = 1;
int num;
cout<<"Enter the 5 numbers:"<<endl;
int sum = 0;
while(x <= 5){
cin>>num;
x++;
sum = sum+num;
}
cout<<"Sum is "<<sum;
}
Output : Enter the 5 numbers
1
2
…..
5
Sum is 15

Program : Age Average.


#include <iostream>
using namespace std;
int main()
{
int age;
int ageTotal = 0;
int numOfPeep = 0;
cout<<"Enter the first person's age or -1 to quit"<<endl;
cin>>age;
while(age!=-1){ \\ as long as age is not -1 it will be executed.
ageTotal = ageTotal + age;
numOfPeep++; \\ Every time it gets added by 1. For every new age.

cout<<"Enter the next person's age or -1 to quit"<<endl;


cin>>age;
} \\ gets out of the loop when age = -1.
cout<<"Number of people "<<numOfPeep<<endl;
cout<<"Average of Age is "<<ageTotal/numOfPeep<<endl;
}
Output:
Enter the first person's age or -1 to quit
13
Enter the next person's age or -1 to quit
15
Enter the next person's age or -1 to quit
20
Enter the next person's age or -1 to quit
25
Enter the next person's age or -1 to quit
-1
Number of people 4
Average of Age is 18

Assignment Operators :
1) x+=5 x =x+5
2) x-=5 x=x-5
3) x*=5 x=x*5
4) x/=5 x=x/5
5) x%=5 x=x%5
Increment Operators:
x++ first read the value and then x = x+1;
x-- first read and then x = x-1;
++x first x = x+1 and then read.
--x first x = x-1 and then read.
#include <iostream>
using namespace std;
int main()
{
int a,b,c,d;
a=b=c=d=6;
cout<<a++<<endl; \\first read and then increment=6;
cout<<a<<endl; \\ new incremented value = 7;

cout<<++b<<endl; \\ first increment and then read = 7;


cout<<b<<endl; \\ value = 7;

cout<<c--<<endl; \\ first read and then decrement = 6;


cout<<c<<endl; \\ new decremented value = 5;

cout<<--d<<endl; \\ first decrement and then read = 5;


cout<<d<<endl; \\ value = 5;
return 0;
}

FOR LOOP : for(initialization; condition ; increment/decrement)


Simple interest calculator.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float a; \\ amount
float p = 8000; \\ principal amount
float r = 0.0567; \\ rate
for(int day = 1; day<=6;day++){ \\ starting with 1st day and calculating the total amount
with interest on last day.
a= p*pow(1+r,day);
cout<<day<<"---"<<a<<endl;
}
}

Do while loop: exit loop. It executes first and then checks the condition. It is useful where
the execution is required atleast once. Even if the condition is false the loop is executed
once.
#include<iostream>
Using namespace std;
int main(){
int x = 1;
do{
cout<<x<<endl;
x++;
}while(x<=5);
}
Output: 1
2
….
5

Switch statement :
using namespace std;
int main()
{
int age;
cout<<"Enter the age \n";
cin >> age;
switch(age) \\ switch(Parameter) and then body.
{
case 18:
cout<<"You can have a license";
break;
case 19:
cout<<"You should get an internship";
break;
case 20:
cout<<"Get a job";
break;
case 21:
cout<<"Legal age";
break;
default :
cout<<"Sorry not mature enough";
}
}

Logical Operators :
&& : and operator, only if both the test cases are true. It runs the statement.
||: or operator, if one of them is true it executes.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age;
cout<<"Enter your age \n";
cin>> age;
int marks;
cout<<"Enter your marks \n";
cin>> marks;
string board;
cout<<"Enter the board name \n";
cin>> board;

if(age>18 && marks>86){ \\ && operator(AND)


cout<<"You can apply for college \n";
}
if(age<18){
cout<<"Not eligible ";
}
if(age>18 || board=="SSC"){ \\ || operator(OR)
cout<<"Contact for more details about SSC ";
}
return 0;
}

Random Number Generator :


rand() : This function returns numbers randomly but following some algorithm. But every
time it follows the same pattern of numbers.
#include <iostream>
#include <cstdlib> \\ c standard library for rand().
using namespace std;
int main()
{
for(int i = 0; i<25;i++){
cout<< rand()<<endl;
}
}

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
srand(19); \\ it changes the algorithm of random numbers(different numbers are
printed), every time you pass a different number.
for(int i = 0; i<25;i++){

cout<< rand()<<endl;
}
}

#include <iostream>
#include <cstdlib>
#include <ctime> \\ to include the time() function.
Using namespace std;

int main()
{
srand(time(0)); \\ now everytime it will print different set of numbers.
for(int i = 0; i<25;i++){

cout<< rand()<<endl;
}
}
Default Arguments: We pass the function with some default parameters so that when the
user doesn’t pass the argument explicitly we use the default ones.
#include <iostream>
using namespace std;

int volume(int l = 1, int b = 1, int h = 1)\\ default arguments passed.


{
return l*b*h;
}
int main()
{
cout<<volume(5); \\ user doesn’t pass all the 3 parameters, so ‘5’ is assigned to only ‘l’.
b&h are automatically set to default value 1.
return 0;
}

Unary Scope Resolution(::) :


1) If you declare a variable outside the function, any function can have access to it.
2) If you declare the variable inside main() or any other function , only that specific
function can have access to it.
#include <iostream>
using namespace std;
int x =30; \\ Global variable(outside the function)
int main()
{
int x=25; \\ local variable(inside)
cout<< ::x; \\ :: this makes use of GLOBAL VARIABLE. So prints “30”.
\\ if not “::”, it prints “25”.
}

FUNCTION OVERLOADING: Function with same name but different type of parameters.
So depending on the input the function with respective parameter is called.
#include <iostream>
using namespace std;

void square(int x){ \\ takes int as a parameter.


cout<<"Square is "<<x*x<<endl;
}

void sqaure(float y){ \\ takes float as a parameter.


cout<<" sqaure of decimal is "<<y*y;
}

int main()
{
int a;
cout<<"Enter the integer \n";
cin>> a;
float b;
cout<<"Enter the float number \n";
cin>> b;
square(a); \\ square(int x) is called.
sqaure(b); \\ square(float y) is called.
return 0;
}

RECURSION : 1) Function calls itself.


2) The function body has a function itself in which it has a function itself.
3) BASE CONDITION should be present, which acts as a terminating point for the
loop.

Ex. FACTORIAL of number :


#include <iostream>
using namespace std;

int factorialNumb(long x){


if(x==1) \\ Base condition
{
return 1;
}
else{
return x*factorialNumb(x-1); \\ recursive function call
}
}
int main()
{
long a;
cout<<"Enter the number \n";
cin>>a;
cout<<factorialNumb(a);
return 0;
}

ARRAYS : To store multiple values.


int arr[size of array] = { values to be stored};
int arr[5] = {1,2,3,4,5};
indexing starts from 0 to (size – 1).
int main()
{
int arr[5]={2,4,5,6,7};
for(int i = 0;i<=4;i++){
cout<<arr[i]<<endl;
}
}
Output :2
4
5
6
7

Array using loops: For bigger size of array it is used.


int main()
{
int arr[5]; \\ declaring size of array.
for(int i=0;i<=4;i++) \\ traversing through each index.
{
arr[i] = 8; \\ assigning 8 to each element
cout<<i<<"----"<<arr[i]<<endl; \\ printing index and elements.
}
}
0----8
1----8
2----8
3----8
4----8

Sum of elements in an array:


#include <iostream>
using namespace std;

int main()
{
int arr[5]={11,22,45,67,89};
int sum = 0; \\ initializing sum = 0.
for(int i=0;i<=4;i++){
sum= sum+arr[i]; \\ each time the sum is added to the element.
cout<<sum<<endl;
}
}
OUTPUT:11
33
78
145
234
Using arrays in FUNCTION:
#include <iostream>
using namespace std;
void printArray(int Array[],int size); \\ function prototype

int main()
{
int arr1[4]={1,2,3,4};
int arr2[5]={45,67,78,89,99};
printArray(arr1,4); \\ while calling , just mention the name of array. NO [].
cout<<"----"<<endl;
printArray(arr2,5);
}

void printArray(int Array[],int size){


for(int i =0;i<size;i++){
cout<<Array[i]<<endl; \\ Printing the elements in array.
}
}
OUT : 1
2
3
4
----
45
67
78
89
99

Multidimensional Arrays: int arr[row][column] = {{},{}…..} The inner brackets depend on


number of rows, if 3 rows, 3 inner brackets and accordingly column will be added while
typing numbers.
int main(){
int arr[3][4]={{111,222,333,643},{561,782,884,455},{989,999,787,584},};
for(int row =0;row<3;row++) \\ traversing through each row.
{
for(int col=0;col<4;col++){ \\ traversing through each column.
cout<<arr[row][col]<<" "; \\ to print the rows and column.
}
cout<<endl; \\ start with a next line after each row.
}
} OUT: 111 222 333 643
561 782 884 455
989 999 787 584
POINTERS: A special type of variable that points to a memory address of a variable.
“&variable” – it returns the address of the stored variable.
& : address Operator.

Data_type_to_which_pointer_will_point *pointer_name;
int *xPointer;

int main()
{
int x = 8;
cout<<&x<<endl;
int *xPointer; \\ Pointer declared.
xPointer = &x; \\ Address to be stored in pointer.
cout<<xPointer<<endl;
return 0;
} OUT : 0x6dfef8
0x6dfef8

PASS BY VALUE : This means we are passing only the copy of the variable but not the
original variable. So we don’t have direct access to the original value.
PASS BY REFERENCE: It means we are passing the variable address. So we have direct
access to the address of the variable , thereby we can change the original one.

void passByValue(int x);


void passByReference(int *x);

int main()
{
int a = 8;
int b = 9;
passByValue(a); \\ calling it, doesn’t change the value of a. Since it has no direct accesss.
passByReference(&b); \\ it changes the value because it has direct access to its address.
While calling use ‘&’ operator for address.
cout<<" a is now "<<a<<endl;
cout<<"b is now "<<b<<endl;
}
void passByValue(int x){ \\ This only has a copy of variable i.e. a
x = 90;
}

void passByReference(int *x){ \\ This has address of the variable.


*x = 88;
}
sizeof : It returns the size of variable, array ,etc.
int main()
{
char c;
cout<<sizeof(c)<<endl; \\ returns the size of character = 1;
int a;
cout<<sizeof(a)<<endl; \\ returns size of “int” = 4;
double d;
cout<<sizeof(d)<<endl; \\ returns size of “double” = 8;

double arr[8];
cout<<sizeof(arr)<<endl; \\ arr size = 8. Double size = 8. Total size of arr = 8*8.
cout<<sizeof(arr)/sizeof(arr[0])<<endl; \\ total size/size of each element = 64/8.
}
OUT : 1 \\ char
4 \\ int
8 \\ double
64\\ total arr size
8

Pointers and Math: Not changing the address, but only changing the address it points to.
int main()
{
int arr[4]; \\ arr defined of size 4.
int *arr0 = &arr[0];
int *arr1 = &arr[1]; \\ pointers pointing to the memory address of elements of arr.
int *arr2 = &arr[2];
int *arr3 = &arr[3];
cout<<"arr[0] is at "<<arr0<<endl;
cout<<"arr[1] is at "<<arr1<<endl; \\ returns the memory address.
cout<<"arr[2] is at "<<arr2<<endl;
cout<<"arr[3] is at "<<arr3<<endl;

arr0 += 1; \\ this actually means, the arr0 pointer now points to memory address
one step away i.e. arr1 , so returns memory add of arr1
cout<<"arr[0] is now at "<<arr0<<endl;
arr1 += 2; \\ arr1 points to memory address 2 steps away i.e. arr3,
returns memory add of arr3.
cout<<"arr[1] is now at "<<arr1<<endl;
} OUT: arr[0] is at 0x6dfee0
arr[1] is at 0x6dfee4
arr[2] is at 0x6dfee8
arr[3] is at 0x6dfeec
arr[0] is now at 0x6dfee4
arr[1] is now at 0x6dfeec
Arrow Member Selection : While using a pointer inside a class i.e. creating a pointer with
class, use -> to access the functions inside class. Like we use ‘.’ Operator with object to
access the functions of class. Similarly -> with pointers.
CHECK CODE ON CODEBLOCKS.

Deconstructor:
1) When the main program ends , the deconstructor is called.
2) There are no parameters or return statements as in constructor.

Main : protected:

#include <iostream> private:


#include "SAG.h" };
using namespace std; #endif
int main()
{ #include "SAG.h" \\ CPP FILE
SAG obj; #include <iostream>
cout<<" I am main"<<endl; using namespace std;
} SAG::SAG()
{
#ifndef SAG_H \\ HEADER FILE cout<<"I am constructor "<<endl;
#define SAG_H }
class SAG SAG::~SAG()
{ {
public: cout<<"I am deconstructor"<<endl;
SAG(); }
~SAG(); \\ deconstructor.

CONSTANT : If you use “const” before any variable or object or function, it is constant
throughout the program. We cannot change the value.

Const objects can only call const functions.

CPP file:
#include "SAR.h"
#include <iostream>
using namespace std;
SAR::SAR(){
}

void SAR::print(){ \\ Normal function


cout<<"Normal function"<<endl;
}
void SAR::print2() const{ \\ const term used after the function, constant function.
cout<<"Constant Function"<<endl;
}

HEADER FILE:
#ifndef SAR_H
#define SAR_H
class SAR
{
public:
SAR();
void print(); \\ function prototype
void print2() const;

protected:

private:
};
#endif

MAIN :
#include <iostream>
#include "SAR.h"
using namespace std;

int main()
{
SAR obj; \\ Normal object
obj.print();
const SAR constObj; \\ constant object, writing “const” before declaring.
constObj.print2();
}
MEMBER INITIALIZERS:
1) Whenever we have a constant variable inside a class, we can’t initialize it in regular
way.
2) The Member initializers are used. The variables are passed as list before the body of
code. The variables are separated by commas.
Header file
#ifndef SAR_H
#define SAR_H
class SAR
{
public:
SAR(int a,int b); \\ constructor defined with two parameters for the two variables
void print(); \\ function to print.

protected:
private:
int regVar; \\ regular variable
const int constVar; \\ constant variable
};
#endif
CPP
include "SAR.h"
#include <iostream>
using namespace std;

SAR::SAR(int a, int b)
: regVar(a), constVar(b) \\ Member initialization, NO ; at the end.
{
}

void SAR::print(){
cout<<"Regular variable "<<regVar<<endl;
cout<<"Constant var "<<constVar<<endl;
}
Main
#include <iostream>
#include "SAR.h"
using namespace std;
int main()
{
SAR obj(34,88);
obj.print();
}
OUT : Regular variable 34
Constant var 88
COMPOSITION: When an object of a one class is used as a member in another class.

Program of birthday :
1) Create two class Birthday and People.
2) Pass the object of Birthday as a variable in People class.

Birthday Header File:


#ifndef BIRTHDAY_H
#define BIRTHDAY_H
using namespace std;
class Birthday
{
public:
Birthday(int d, int m,int y); \\ constructer declared through arguments.
void print();
private:
int date;
int month;
int year;
};
#endif

Birthday CPP :
#include "Birthday.h"
#include <iostream>
using namespace std;
Birthday::Birthday(int d,int m,int y)
{
date = d;
month = m;
year = y;
}
void Birthday::print() \\ “print function” to print dates.
{
cout<<date<<"/"<<month<<"/"<<year<<endl;
}

People Header file:


#ifndef PEOPLE_H
#define PEOPLE_H
#include<string>
#include "Birthday.h" \\ must include Birthday header.
using namespace std;
class People
{
public:
People(string n, Birthday dB); \\ name and object of Birthday class as parameter.
void printName();
private:
string name;
Birthday dob; \\ use object of Birthday as variable.
};
#endif

People CPP file:


#include "People.h"
#include "Birthday.h"
#include <iostream>
using namespace std;
People::People(string n, Birthday dB)
: name(n),dob(dB) \\ MEMBER INITIALIZATION..
{
}
void People::printName(){
cout<<name<<" was born on ";
dob.print(); \\ using it to print() of Birthday class.
}

MAIN:
#include "Birthday.h"
#include "People.h"
#include <iostream>
using namespace std;
int main()
{
Birthday dateobj(26,07,2000);
People nameobj("Tanvi Kedar",dateobj);
nameobj.printName(); \\ TO print everything.
return 0;
}
Friend Function : A function which has access to all the members of the class though it is
not written inside the class, only prototyped in the class.
#include <iostream>
using namespace std;

class ABC{
public:
ABC() \\ ABC constructor to set the initial value = 0;
{
int abc=0;
}
private:
int abc;

friend void printfriend(ABC &ob); \\ friend function which has access to member of ABC.
};
void printfriend(ABC &ob) \\ declared outside class. Pass the object of ABC(class) as
argument.
{
int abc=8;
cout<<abc<<endl;
}
int main()
{
ABC obj;
printfriend(obj); \\ object(“obj”) passed as a parameter.
return 0;
}
OUT : 8

THIS: It stores the address of the object and the variables used.

Header file: CPP file:


#ifndef THI_H #include "THI.h"
#define THI_H #include <iostream>
class THI using namespace std;
{ THI::THI(int a)
public: : num(a) \\ member initialization.
THI(int a); {
void print(); }
private: void THI::print(){
int num; cout<<" num is "<<num<<endl;
}; cout<<"this-> "<<this->num;\\ acts as a
pointer
}
MAIN:
#include <iostream>
#include "THI.h"
using namespace std;
int main()
{
THI obj(88);
obj.print();
}
OUT : num is 88 \\ same output
this-> 88

OPERATOR OVERLOADING: With the help of this, we can add the two objects of the same
class.
#include <iostream>
using namespace std;

class OPO{
private :
int num;
public :
OPO(int a=0){ \\ Constructor to pass the parameter.
num = a;
}
OPO operator + (OPO aO) \\ Syntax first object + another object of OPO
{
OPO res; \\ To return a new object.
res.num = num + aO.num;
return res; \\ this returns the object.
}
void print(){
cout<<"sum is "<<num;
}
};

int main()
{
OPO obj1(20); \\ two objects created to pass the numbers.
OPO obj2(28);
OPO obj3 = obj1+obj2; \\ Operator Overloading
obj3.print();
}
OUT : sum is 48.
Following is the list of operators that cannot be overloaded.
. (dot)
::
?:
sizeof

INHERITANCE: Properties of base class are inherited by the derived class.


Syntax: class derived_class : public base_class{};
#include <iostream>
using namespace std;

class Parent{ \\ Base class


public:
void callName(){
cout<<"Mano Ghode"<<endl;
}
};

class Son:public Parent{ \\ derived class.


public:
void print(){
cout<<"SG"<<endl;
}
};

int main()
{
Son obj; \\ Object of derived class.
obj.callName();
obj.print();
}
Derived class can inherit ONLY public and protected members NOT private members of
BASE CLASS.

Constructor and Deconstructor of Base & Derived:


#include <iostream>
using namespace std;
class Parent{
public:
Parent(){
cout<<"Parent Constructor"<<endl;
}
~Parent(){
cout<<"Parent Deconstructor"<<endl;
}
};

class Son:public Parent{


public:
Son(){
cout<<"Son constructor"<<endl;
}
~Son(){
cout<<"Son Deconstructor"<<endl;
}
};
int main()
{
Son obj;
}
Out : Parent Constructor
Son constructor
Son Deconstructor
Parent Deconstructor

1) When the object of derived class is called, it first instantiates the base class
Constructor.
2) While leaving the program, first the derived class deconstructor is instantiated and
then the base class.

POLYMORPHISM:
C++ polymorphism means that a call to a member function will cause a different function to be
executed depending on the type of object that invokes the function.
#include <iostream>
using namespace std;

class Enemy{
protected:
int attack;
public:
void setattack(int a){
attack = a;
}
};

class Ninja:public Enemy{ \\ Derived class


public:
void showattack(){
cout<<"Ninja has "<<attack<<endl;
}
};

class Monster:public Enemy{


public:
void showattack(){
cout<<"Monster has "<<attack<<endl;
}
};
int main()
{
Ninja n;
Monster m;
Enemy *enemyPointer1 = &n; \\ pointer which will store the address of the object.
Enemy *enemyPointer2 =&m;
enemyPointer1->setattack(88);
enemyPointer2->setattack(99);
n.showattack();
m.showattack();
}
OuT: Ninja has 88
Monster has 99

S-ar putea să vă placă și