Professional Documents
Culture Documents
C
C
C
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
}
C++ Variables
Variables are containers for storing data values.
In C++, there are different types of variables (defined with different
keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123
or -123
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
Syntax
type variable = value;
Where type is one of C++ types (such as int), and variable is
the name of the variable (such as x or myName). The equal
sign is used to assign values to the variable.
Example
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable
'myNum'
C++ Input
In C++, cin takes formatted input from standard input devices such
as the keyboard. We use the cin object along with the >> operator
for taking input.
Example 3: Integer Input/Output
#include <iostream>
int main() {
int num;
cout << "Enter an integer: ";
cin >> num; // Taking input
cout << "The number is: " <<
num;
return 0;
}
Output
Enter an integer: 70
The number is: 70
Type Casting
The syntax for this style is:
(data_type)expression;
For example,
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
Example 1: Arithmetic Operators
#include <iostream>
using namespace std;
int main() {
int a, b;
a = 7;
b = 2;
// printing the sum of a and b
cout << "a + b = " << (a + b) << endl;
return 0;
}
Increment and Decrement Operators
C++ also provides increment and decrement operators: ++
and -- respectively. ++ increases the value of the operand by
1, while -- decreases it by 1.
For example,
int num = 5;
// increasing num by 1
++num;
Here, the value of num gets increased to 6 from its initial
value of 5.
C++ Assignment Operators
In C++, assignment operators are used to assign values to
variables. For example,
a = 5;
Here, we have assigned a value of 5 to the variable a.
int main() {
int a, b, temp;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
// value of a is assigned to temp
temp = a; // temp will be 2
cout << "temp = " << temp << endl;
return 0;
}
Output
temp = 2
a=9
C++ Relational Operators
A relational operator is used to check the relationship
between two operands. For example,
int main() {
int a, b;
a = 3;
b = 5;
bool result;
return 0;
}
Output
3 == 5 is 0
3 != 5 is 1
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1
Note: Relational operators are used in decision
making and loops.
C++ Logical Operators
Logical operators are used to check whether an expression is true or false. If
the expression is true, it returns 1 whereas if the expression is false, it
returns 0.
Suppose,
a=5
b=8
Then,
Operator Description
& Binary AND
| Binary OR
^ Binary XOR
~ Binary One's Complement
<< Binary Shift Left
>> Binary Shift Right
C++ comments are hints that a programmer can add to
make their code easier to read and understand. They are
completely ignored by C++ compilers.
/* */ -Multi-line Comments
Single Line Comments
In C++, any line that starts with // is a comment. For example,
int a;
// initializing the variable 'a' with the value 2
a = 2;
Multi-line comments
In C++, any line between /* and */ is also a comment. For
example,
/* declaring a variable
to store salary to employees
*/
int salary = 2000;
if...else statements in C++.
if statement
if...else statement
if...else if...else statement
C++ if Statement
The syntax of the if statement is:
if (condition) {
// body of if statement
}
The if statement evaluates the condition inside the
parentheses ( ).
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
The if..else statement evaluates the condition inside the
parenthesis.
If the condition evaluates true,
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
If condition1 evaluates to true, the code block 1 is
executed.
If condition1 evaluates to false, then condition2 is
evaluated.
If condition2 is true, the code block 2 is executed.
If condition2 is false, the code block 3 is executed.
C++ if...else...else if
// Program to check whether an integer is positive, negative or
zero
#include <iostream>
int main() {
int number;
Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.
Output 2
Enter an integer: -2
You entered a negative integer: -2.
This line is always printed.
Output 3
Enter an integer: 0
You entered 0.
This line is always printed.
Nested if...else
Sometimes, we need to use an if statement inside another if
statement. This is known as nested if statement. // outer if
statement
if (condition1) {
// statements
// inner if statement
if (condition2) {
// statements
}
}
Notes:
// outer if condition
if (num != 0) {
// inner if condition
if ((num % 2) == 0) {
cout << "The number is even." << endl;
}
// inner else condition
else {
cout << "The number is odd." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither even nor
odd." << endl;
}
cout << "This line is always printed." << endl;
}
In computer programming, loops are used to repeat a
block of code.
for loop
while loop
do...while loop
C++ for loop
The syntax of for-loop is:
int main() {
for (int i = 1; i <= 5; ++i)
{
cout << i << " ";
}
return 0;
}
Output
12345
#include <iostream>
int main() {
int num, sum;
sum = 0;
return 0;
}
C++ Infinite for loop
If the condition in a for loop is always true, it runs forever
(until memory is full). For example,
while (condition) {
// body of the loop
}
do {
// body of loop;
}
while (condition);
The body of the loop is executed at first. Then the condition
is evaluated.
If the condition evaluates to true, the body of the loop
inside the do statement is executed again.
The condition is evaluated once again.
If the condition evaluates to true, the body of the loop
inside the do statement is executed again.
This process continues until the condition evaluates to
false. Then the loop stops.
#include <iostream>
using namespace std;
int main()
{
int n1, n2, max;
continue;
The switch statement allows us to execute a block of code
among many alternatives.
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
In C++ programming, goto statement is used for altering the
normal sequence of program execution by transferring control to
some other part of the program.
Syntax of goto Statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
... .. ...
In the syntax above, label is an identifier. When goto label; is
encountered, the control of program jumps to label: and
executes the code below it.
# include <iostream>
using namespace std;
Largest and smallest
int main()
{
float num, average, sum = 0.0;
int i, n;
void prime();
int main()
{
// No argument is passed to prime()
prime();
return 0;
}
void prime() // Return type of function is void because value is not returned.
{
int num, i, flag = 0;
prime() takes the positive number from the user and checks
whether the number is a prime number or not.
int prime();
int main()
{
int num, i, flag = 0;
if (flag == 1)
{
cout<<num<<" is not a prime number.";
}
else
{
cout<<num<<" is a prime number.";
}
return 0;
}
// Return type of function is int
int prime()
{
int n;
printf("Enter a positive integer to check: ");
cin >> n;
return n;
}
In the above program, prime() function is called from
the main() with no arguments.
In the above program, positive number is first asked from the user which is
stored in the variable num.
Then, num is passed to the prime() function where, whether the number is
prime or not is checked and printed.
Since, the return type of prime() is a void, no value is returned from the
function.
Example 4: Arguments passed and a return value.
#include <iostream>
using namespace std;
int main()
{
int num, flag = 0;
cout << "Enter positive integer to check: ";
cin >> num;
Then, num is passed to the function prime() where, whether the number
is prime or not is checked.
Notice that the return types of all these 4 functions are not the
same. Overloaded functions may or may not have different
return types but they must have different arguments. For
example,
// Error code
int test(int a) { }
double test(int b){ }
Here, both functions have the same name, the same type, and
the same number of arguments. Hence, the compiler will throw
an error.
Function Overloading using Different Types of Parameter
// Program to compute absolute value
// Works for both int and float
#include <iostream>
using namespace std;
int main() {
int a = 5;
double b = 5.5;
return 0;
}
Output
Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5
// C++ program to overload sum() function
#include <iostream>
using namespace std;
int main() {
// Call function with 2 int parameters
cout << "Sum 1 = " << sum(5, 6) << endl;
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18
Introduction to C++ Classes and Objects
The classes are the most important feature of C++ that leads to
Object Oriented programming. Class is a user defined data type,
which holds its own data members and member functions,
which can be accessed and used by creating instance of that
class.
public
private
protected
These access modifiers are used to set boundaries for availability
of members of class be it data members or member functions
double calculateArea() {
return length * breadth;
}
double calculateVolume() {
return length * breadth * height;
}
};
int main() {
// create object of Room class
Output
Room room1;
Area of Room = 1309
// assign values to data members Volume of Room = 25132.8
room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;
class PrivateAccess
{
// private access modifier
private:
int x; // Data Member Declaration
void display(); // Member Function decaration
}
#include <iostream>
using namespace std;
class Room {
private:
double length;
double breadth;
double height;
public:
// function to initialize private variables
void getData(double len, double brth, double hgt) {
length = len;
breadth = brth;
height = hgt;
}
double calculateArea()
{
return length * breadth;
}
double calculateVolume()
{
return length * breadth * height;
}
};
int main() {
return 0;
}
#include <iostream>
#include<string>
using namespace std;
class Car
{ public:
string brand;
string model;
int year;
};
int main()
{
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Create another object of Car
Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;
// Print attribute values
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n"; return 0;
}
C++ Constructors
A constructor is a special type of member function that is called
automatically when an object is created. A constructor has the same
name as that of the class and it does not have a return type. For
example,
class Wall {
public:
// create a constructor
Wall() {
// code
}
};
#include <iostream>
using namespace std;
class Wall {
private:
double length;
public:
// create a constructor
Wall() {
// initialize private variables
length = 5.5;
cout << "Creating a wall." << endl;
cout << "Length = " << length << endl;
}
};
int main() {
// create an object
Wall wall1;
return 0;
}
Output:
Creating a Wall
Length = 5.5
C++ Parameterized Constructor
In C++, a constructor with parameters is known as a
parameterized constructor.
#include <iostream>
using namespace std;
// declare a class
class Wall {
private:
double length;
double height;
public:
// create parameterized constructor
Wall(double len, double hgt) {
// initialize private variables
length = len;
height = hgt;
}
double calculateArea()
{
return length * height;
}
};
int main() {
// create object and initialize data members
Wall wall1(10.5, 8.6);
Wall wall2(8.5, 6.3);
return 0;
}
C++ Destructor
A destructor works opposite to constructor; it destructs the
objects of classes. It can be defined only once in a class. Like
constructors, it is invoked automatically.
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked
C++ Inheritance
In C++, inheritance is a process in which one object acquires all
the properties and behaviors of its parent object automatically. In
such way, you can reuse, extend or modify the attributes and
behaviors which are defined in other class.
derived class (child) - the class that inherits from another class
base class (parent) - the class being inherited from
To inherit from a class, use the : symbol.
Derived Classes
A Derived class is defined as the class derived from the base class.
The Syntax of Derived class:
//Base class
class Parent
{
public:
int id_p;
};
// Sub class inheriting from Base Class(Parent)
class Child : public Parent
{
public:
int id_c;
};
//main function
int main()
{
Child obj1;
// An object of class child has all data members
// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
return 0;
}
Output:
Child id is 7
Parent id is 91
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
// Calling members of the base class
dog1.eat();
dog1.sleep();
return 0;
}
Passing objects to a function
In C++ programming, we can pass objects to a function in a similar manner
as passing regular arguments.
C++ Pass Objects to Function
// C++ program to calculate the average marks of two students
#include <iostream>
using namespace std;
class Student {
public:
double marks;
// constructor to initialize marks
Student(double m) {
marks = m;
}
};
// function that has objects as parameters
void calculateAverage(Student s1, Student s2) {
// calculate the average of marks of s1 and s2
double average = (s1.marks + s2.marks) / 2;
cout << "Average Marks = " << average << endl;
}
int main() {
Student student1(88.0), student2(56.0);
// pass the objects as arguments
calculateAverage(student1, student2);
return 0;
}
Output
Average Marks = 72
Polymorphism in C++
The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a
message to be displayed in more than one form. A real-life
example of polymorphism, a person at the same time can
have different characteristics. Like a man at the same time is
a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called
polymorphism. Polymorphism is considered as one of the
important features of Object Oriented Programming.
Function Overloading: When there are multiple functions with
same name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by change in number of
arguments or/and change in type of arguments.
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
void func(int x) // function with 1 int parameter
{
cout << "value of x is " << x << endl;
}
// function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}
:: .* . ?:
#include <iostream>
#include <conio.h>
using namespace std;
class test
{
private:
int x;
int y;
int z;
public:
void getdata(int a,int b,int c);
void display() ;
void operator-();
};
void test::getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void test::display()
{
cout<<x<<" ";
cout<<y<<" ";
cout<<z<<" ";
}
void test::operator-()
{
x=-x; y=-y; z=-z;
}
int main()
{
test N;
N.getdata(10,-20,30);
N.display();
-N;
cout<<"Displaying after operator overloading";
N.display();
return 0;
}
Function Overriding
When the base class and derived class have member functions
with exactly the same name, same return-type, and same
arguments list, then it is said to be function overriding.
Requirements for Overriding a Function
Inheritance should be there. Function overriding cannot be
done within a class. For this we require a derived class and a
base class.
Function that is redefined must have exactly the same
declaration in both base and derived class, that means same
name, same return type and same parameter list
Difference between function overloading and function overriding
1) Function Overloading happens in the same class when we declare
same functions with different arguments in the same class. Function
Overriding is happens in the child class when child class overrides parent
class function.
2) In function overloading function signature should be different for all
the overloaded functions. In function overriding the signature of both the
functions (overriding function and overridden function) should be same.
3) Overloading happens at the compile time thats why it is also known as
compile time polymorphism while overriding happens at run time which
is why it is known as run time polymorphism.
4) In function overloading we can have any number of overloaded
functions. In function overriding we can have only one overriding
function in the child class.
#include <iostream>
using namespace std;
class A {
public:
void display() {
cout<<"Base class";
}
};
class B:public A {
public:
void display() {
cout<<"Derived Class";
}
};
int main()
{
B obj;
obj.display();
return 0;
}
It will produce the following
output
Derived Class
class Base
{
public:
void show()
{
cout << "Base class\n";
}
};
class Derived:public Base
{
public:
void show()
{
cout << "Derived Class\n";
}
};
int main()
{
Base *b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Early Binding Occurs
}
Virtual Function in C++
A virtual function is a member function which is declared within a
base class and is re-defined(Overriden) by a derived class. When we
refer to a derived class object using a pointer or a reference to the
base class, we can call a virtual function for that object and execute
the derived class’s version of the function.
void show()
{
cout << "show derived class" << endl;
}
};
int main()
{
base* bptr;
derived d;
bptr = &d;
// virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
}
Output:
print derived class
show base class