C++ intro
C++ intro
C++ is an object-oriented programming language. C++ us a middle level language developed by Bjarne Stroustrup
starting in 1979 at Bell labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the Various
version of UNIX. C++ was developed as an extension to the c language. It is fast portable and available on all
platform. C++ is an object-oriented programming language but is not purely Object Oriented. Its features
like Friend and Virtual, violate some of the very important OOPS features, rendering this language
unworthy of being called completely Object Oriented. Its a middle level language.
Why Learn C++?
C++ is one of the most used and popular programming languages. C++ is used in making operating systems,
embedded systems, distributed system, games, animation ,banking application and Graphical User Interfaces. It
supports object-oriented programming and implements all the OOP concepts such as Abstraction, Encapsulation,
and Inheritance, which gives a clear structure to programs and allows code to be reused, lowering development
costs and providing security. It makes programming easy for programmers to switch to C++ because its syntax is
similar to C, Java, and C#. C++ is faster than Python and Java. When compared to C, C++ has richer libraries,
supports object-oriented programming, templates, exception handling and many more features.
Difference between C and C++
C Programming C++ Programming
2. Object-Oriented Programming :-C++ follows the concept of OOPS, which includes classes, members,
polymorphism, inheritance, abstraction, etc., which leads to easier maintenance and development.
3. Portability:-programs written in c++ can be run on almost all machine with little or no modification. C++ is
not platform-independent but portable enough to allow for minor changes.
4. Middle-Level Language :- C++ has the ability to do both low-level and high-level programming, which is
why it is also referred to as the mid-level programming language. When we talk about low-level programming,
C++ is used to develop system applications such as the kernel, driver, etc.
5. Dynamic Memory Allocation:- Variables in a C++ program are allocated to the dynamical heap space when
it runs, whereas variables inside functions are allocated to the stack space. We frequently do not know how
much memory is required to store specific information in a defined variable, and the required memory size can
be determined at run time.
6. Case-sensitive:-As C++ originated from C, it also maintains pure CASE sensitivity, implying that lowercase
and uppercase characters written in code will have distinct meanings and receive different treatment.
7. Fast Speed:-It is a fast language because its compilation and execution times are relatively short. It supports
numerous data types, functions, and operators.
8. Memory Management:-It also supports dynamic memory allocation, which allows us to allocate variable or
array memory during execution. Unlike in Java or Python, memory must be manually de-allocated when it is no
longer needed.
9. Multi-threading:-The central processing unit (CPU) feature known as multithreading enables two or more
instruction threads to run concurrently and independently while sharing the same process resources. An
independent set of instructions called a thread can run concurrently with other threads belonging to the same root
process. A single process can carry out several concurrent tasks, thanks to multithreading. Comparing
multithreaded programming to conventional parallel multiprocessing programs can speed up machine learning
algorithm training for data scientists. Since C++ does not come with built-in support for multithreaded programs,
the operating system must provide it.
10. Dynamic Memory Allocation:-Variables in a C++ program are allocated to the dynamical heap
space when it runs, whereas variables inside functions are allocated to the stack space. We frequently
do not know how much memory is required to store specific information in a defined variable, and
the required memory size can be determined at run time.
11. Rich Library:-The C++ library is jam-packed with built-in functions that save significant time
during the software development process. It includes almost every type of functionality that a
programmer might require during the development process. As a result, time is saved, and
development speed is increased.
<cmath>: contains math functions
<ctime>: contains function for changing time and date
<fstream>: contains functions for performing input from and output to files on disk.
12. Integration and Extensibility:-Object-oriented support allows C++ programs to be maintainable
and extensible, allowing for the creation of large-scale applications. C++ can integrate and implement
newer features easily. It has been used successfully in various applications, including mobile app and
game development, software development, web browser development, and bank applications.
Drawbacks of C++
Complexity: Large Programs are hard to be Programmed in C++ as the code gets too big to handle.
Platform Dependent: C++ is not a Platform Independent language like Java and has to be written
for different Operating System Independently o be run everywhere making it a huge process
Incapables of Programming web application : C++ is not sued for Web Applications because of
the huge amount of Code required and the difficulty of Debugging which is much simpler in
Languages like PHP and JavaScript
Object Oriented Programming
Object oriented programming is a programming technique in which programs are written on the basis of
objects. Object-Oriented Programming is the heart of modern software development, and C++
programming stands as one of its most powerful champions. By combining logical structure with real-
world solving, C++ OOP transforms abstract ideas into efficient, modular, and scalable solutions.
Whether you are building dynamic applications or managing complex systems, C++ OOPs offers tools
to turn possibilities into realities. Let us go through the article to learn more about C++ OOP.
The benefits of OOP in C++ make it a powerful paradigm for building both simple and complex
applications. From organizing code and enhancing security to enabling reusability and scalability, OOP
helps developers write clean, maintainable, and future-proof software. It is like having a well-organized
toolbox where each tool has its place, purpose, and ability to work seamlessly with others.
Advantages of oops :
1. Software complexity can be easily managed.
2. This principle of data hiding helps the programmer to build secure programs that can’t be invaded by
code in other parts of the program.
3. It is easy to partition the work in a project based on objects.
4. Modularity and Code Organization: OOP allows us to structure our program into classes and
objects, making the code easier to understand and manage. Each class represents a specific concept or
functionality, breaking down the complexity of large programs into smaller, manageable pieces.
5. Reusability through Inheritance: With inheritance, we can reuse existing code by creating new
classes based on previously written ones. This reduces redundancy, saves development time, and ensures
consistency.
6. Encapsulation for Data Security: Encapsulation hides the internal details of objects and only exposes
necessary parts through public methods. This ensures that data is accessed and modified in a controlled
way, reducing the risk of accidental interference or misuse.
7. Ease of Maintaining and Scalability: OOP makes it easier to maintain and scale the software. When
requirements change, we can modify or extend specific parts of the program without affecting the entire
system. This modular approach also simplifies debugging and testing.
8. Easier Debugging and Error Handling: By isolating functionality into separate classes, OOP makes
it simpler to identify and fix bugs. Errors are usually contained within a specific class, reducing their
impact on the overall system.
C++ Program Structure
#include<iostream>
using namescape std;
int main()
{
cout<<“hello world”;
}
Note :- A header file is used to define a library that you want to use in the programs. <iostream> is
library responsible for printing a message on the screen and accepting a value from the user. The
standard using namespace std; allows to you use elements from the c++ Standard library without
explicitly prefixing them with std::;
Tokens in C++
In a C++ program, a collection of all the keywords, identifiers, operators, special symbols, constants, strings, and
data values are called tokens. Every C++ program is a collection of instructions and every instruction is a
collection of some individual units. Every smallest individual unit of a C++ program is called token. Every
instruction in a C++ program is a collection of tokens. Tokens are used to construct c programs and they are said to
the basic building blocks of a C++ program.
In a C++ program tokens may contain the following...
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values
Keywords in C++
Keywords are predefined or reserved words that have special meanings to the compiler. It Can not be
used for another purpose. Written in lowercase letters. We have 95 keywords in C++ programming.
These are part of the syntax and cannot be used as identifiers in the program.
6. We cannot name identifiers the same as keywords because they are reserved words to perform a
specific task. For example, printf, scanf, int, char, struct, cin, cout etc.
8. C++ language is case-sensitive so, ‘name’ and ‘NAME’ are different identifiers.
Example of Identifier
#include <iostream>
using namespace std;
int main() {
const int con1 = 5; // Declaring and Initializing Constant
const int con2 = 12;
int var1;
int var2;
var1 = 5;
var2 = 12;
var1 = 10; // Changing Variable Values
var2 = 20;
cout << "First Constant = " << con1 << "\n";
cout << "Second Constant = " << con2 << "\n";
cout << "First Variable = " << var1 << "\n";
cout << "Second Variable = " << var2;
}
Basic C++ programs
#include<iostream>
Using namespace std;
void mca();
int main()
{
mca();
return 0;
}
void mca()
{
Cout<<“ hello class”;
}
Data Types in C++
Data Types in C++ :- It specifies the type of data that the variable can store like integer, character,
floating, double, etc. the type of a variable determine how much space it occupies in storage and how
the bit pattern stored is interpreted. In the C++ programming language, every variable needs to be
created with a data type.
The data type of a variable specifies the following.
1. The type of value can be stored in a variable.
2. The amount of memory in bytes has to be allocated for a variable.
3. The range of values has to be stored in a variable.
Types of data types in C++
There are five types of data types in c.
Data Types Example of Data Types
The void data type means nothing or no value. Generally, the void is used to specify a function which does not
return any value. We also use the void data type to specify empty parameters of a function.
An enumerated data type is a user-defined data type that consists of integer constants and each integer constant
is given a name. The keyword "enum" is used to define the enumerated data type.
Derived data types are user-defined data types. The derived data types are also called as user-defined data types
or secondary data types. In the c programming language, the derived data types are created using the following
concepts...
Arrays
Structures
Unions
Enumeration
Data Types in C
Data Type Size (bytes) Range
short int 2 -32,768 to 32,767
0 to 18,446,744,073,709,551,615 added
unsigned long long int 8
by c99
Double double or long double %ld 8 bytes +/- 1.7e +/- 308 (~15 digits)
The variables that are declared inside a function or a block are called local variables. The local
variable is visible only inside the function or block in which it is declared. That means the local
variables can be accessed by the statements that are inside the function or block in which the variable
has declared. Outside the function or block, the local variable can't be accessible.
Scope:- the area where a variable can be accessed is know as scope of variable. Local variable can be
used only in the function in which it is declared . If a statement accesses a local variable that is not in
scope, the compiler generates a syntax error. The life time of local variable starts when the control
enters the function in which it is declared. Local variable is automatically destroyed when the control
exits from the function and its life time ends. When the lifetime of a variable ends the value stored in
this variable also becomes inaccessible.
Global Variables
Global variables are those, which ar once declared and can be used throughout the lifetime of the program
by any class or any function. They must be declared outside the main() function. If only declared, they can
be assigned different values at different time in program lifetime. But even if they are declared and
initialized at the same time outside the main() function, then also they can be assigned any value at any
point in the program.
Its scope is the whole program i.e. we can access the global variable anywhere in the C++ program after it is
declared. Lifetime of global variable is till the termination of the program. the life time of a variable is the
duration in which a variable exists in memory the creation and destruction of the memory variable.
Note: When we have same name for local and global variable, local variable will be given
preference over the global variable by the compiler.
Static Variable in C++: These are similar to instance variables but common to every object of the
class. There is only a single copy of static variables per class and static variables are declared with a
static keyword. Their memory gets allocated at the start of the program and gets destroyed at the
termination of the program. Static variables when used inside function are initialized only once, and
then they hold there value even through function calls. These static variables are stored on static
storage area , not in stack. Their initialization is compulsory and it is done outside the class. by
default, int variable will have a 0 value, boolean will have a false value.
There are 3 aspects of defining a variable:
Variable Declaration
Variable Definition
Variable Initialization
C++ Variable Declaration
The process must be specifying the variable name and its type is called variable declaration.
All they variables must be declared before they used in the program. The variable declaration
provides information to the compiler about the variable. The compiler uses the declaration to
determine how much memory is needed for each variables.
2. C++ Variable Definition
In the definition of a C++ variable, the compiler allocates some memory and some value to it. A defined variable
will contain some random garbage value till it is not initialized.
3. C ++ Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the variable when
creating the variable.
#include <iostream>
using namespace std;
int main(){
int a;
cout<<a;
int a = 12;
int b = 25;
cout<<a;
cout<<b;
return 0; }
Example of Local Variables in C++
#include <iostream>
void local();
int main() {
int a = 22, b = 44;
local();
std::cout << "Values in the main() function a = " << a << " and b = " << b << std::endl;
return 0;
}
void local()
{
int a = 50, b = 80;
std::cout << "Values in the local() function a = " << a << " and b = " << b << std::endl;
}
Example of Local Variables in C++
#include < iostream.h >
using namespace std;
int sum()
{
int a = 10, b = 20;
// cout<< "Result = " << result; // Error - result can't be accessed
return a + b; }
int main()
{
int result;
result = sum();
cout << "Sum = " << result << endl;
// cout << a << "+" << b << "=" << sum() << endl; // Error - a & b are not accessible
return 0;
}
Example of Global Variables in C++
#include <iostream>
using namespace std;
class Sample{
public:
int a, b;
void setData(){
cout << "Enter a and b values: ";
cin >> a >> b;
}
void getData(){
cout << "a = " << a << endl << "b = " << b << endl;
} };
int main() {
Sample s;
s.setData();
s.getData();
return 0;}
Example of static Variables in C++
#include <iostream>
using namespace std;
void mca()
{
static int a=0;
a++;
cout << a;
}
int main()
{
for(int i=0;i<5;i++)
{
mca();
}
return 0;
}
Example of static Variables in C++
#include <iostream>
using namespace std;
void fun() {
static int v = 0;
int a = 10;
v++;
cout << a << " " << v << endl;
}
int main()
{
fun();
fun();
fun();
}
C++ Operators
An operator in C++:- is a symbol that tells the compiler to perform a specific mathematical or logical
operations. It is used in programs to manipulate data and variables. It generally forms mathematical or logical
expressions. An expression is a combination of variables, constants, and operators. Operators are the symbols
that are used to perform different operations on data. If a symbol like +, -, *, etc. is used as an operator, it is
called symbolic operator.
For example, an expression is x + 5. Here, the operand x is a variable, operand 5 is a constant, and + is an
operator that acts on these two operands and produces the desired result.
( +, -, *, /, ) Arithmetic operator
This operator checks whether the value of the left operand is less than the value of the
1. < Less than right operand. If the value on the left side of operator is less than the value on the right
side, the result becomes true.
This operator evaluates that the value of the left operand is less than or equal to the value
2. <= Less than or equal to of the right operand. If it is the case, the operator returns true.
This operator evaluates that the value of the left operand is greater than the value of the
right operand. If the value on the left side of operator is greater than the value on the right
3. > Greater than
side, the greater than (>) operator returns true.
This operator tests that the value of the left operand is greater than or equal to the value of
Greater than or equal to the right operand. If the value on the left side of the operator is greater than or equal to the
4. >=
value on the right side, then the operator returns true.
This operator evaluates that the value of left and right operands is equal or not. If values
5. == Equal to on both sides of the operator are equal to each other, the equal operator (==) returns true.
This operator evaluates that the left operand is not equal to the right side. If the values
6. != Not equal to on both sides of the operator are not equal to each other, the not equal operator returns
true.
Example of Relational Operator
#include <iostream>
using namespace std;
int main() {
int X = 5;
int Y = 5;
cout << "X is Equal to Y : " << (X == Y) << "\n";
cout << "X is not Equal to Y : " << (X != Y) << "\n";
cout << "X is more than Y : " << (X > Y) << "\n";
cout << "X is less than Y : " << (X < Y) << "\n";
cout << "X is more than or equal to Y : " << (X >= Y) << "\n";
cout << "X is less than or equal to Y : " << (X <= Y);
return 0;
}
Truth Table of Gates in C++
Input Output Output Output Output Output
1 1 0 1
0 1 0
1 1 0 1
1 0 0
1 1 0 0 0
1 1
3. Logical operators in C++:- are those operators which are used to form compound conditions by
combining two or more conditions or relations.
These operators are also called boolean operators in c because they return a boolean value of either true
or false after evaluation.
Logical operators combine the more than one comparison into one condition group. It is useful when
we to check more than one condition at a time and want to use the outcome.
Types of Logical (Boolean) Operators in C++
Operators Meaning
2. || OR operator
3. ! NOT operator
Example of logical operators:-
#include <iostream>
using namespace std;
int main() {
int X = 5;
int Y = 10;
cout << "First Condition : " << (X == Y && X != Y) << "\n";
cout << "Second Condition : " << (X < Y || X > Y) << "\n";
cout << "Third Condition : " << !(X == Y);
return 0;
}
Assignment Operator in C++ :- An operator which is used to store a value into a particular variable is called
assignment operator in C++. In any programming language, an assignment operator is the most commonly used
to assign a value to a variable.
There are three categories of assignment operations in C++ programming. They are as follows:
Simple assignment
Compound assignment
Assignment as expression
Simple Assignment
We can use a simple assignment in two ways:
To store or assign a value to a variable.
To store a value of a variable into another variable. For example:
int x = 10;
2. int y = x; // Here, we have stored the value of variable x into y.
Compound Assignment:-
For example:
x += 5; // It is equivalent to int x = x + 5;
x -= 10; // It is equivalent to int x = x – 10;
a *= 100; // Equivalent to int a = a * 100;
a /= (b + c);
Explanation:
x += y; will be evaluated in the following steps:
x += y; is equivalent to x = x + y;
x = 20 + 30;
x = 50;
y -= x + z; is equivalent to y = y – (x + z);
y = y – ( 50 + 50);
y = 30 – 100;
y = -70;
z *= x * y; is equivalent to z = z * (x * y);
z = z * (50 * (-70)); z = 50 * (-3500);
z = -175000;
Assignment as Expression
In C++, we can also consider an assignment operation an expression because the operation has a result. The result
of expression is a value that is stored in a variable. We mainly use it in more than one assignment.
For example:
1. int x = y – z + 4; // Here, the expression y – z + 4 is evaluated first and then its result is stored into the
variable x.
They can be classified into user-defined functions, library functions or built-in functions. Library
functions are predefined functions provided by C++ libraries, while user-defined functions are created
by the programmer.
C++ programming language provides a variety of functions that help perform specific tasks. Functions
in C++ programming enable code reusability, and modular programming, and improve code
readability. They encapsulate a series of instructions into a single unit that can be called whenever
required. Functions in C++ are declared using a return type, function name, and optional parameters.
Why Do We Need Functions?
Functions make code modular. Consider a big file having many lines of code. It becomes really
simple to read and use the code, if the code is divided into functions.
Functions provide abstraction. For example, we can use library functions without worrying about
their internal work.
Advantages of the functions in C++ programming
1. It is used to avoid rewriting the same code again and again in the program (code reusability).
2. It can be called many numbers of times from any place of program blocks.
3. It makes a code modular.
4. It becomes easy to understand and manage.
5. It improves the code readability and organization of the code.
6. They allow programmers to break down complex tasks into smaller, manageable parts, making it
easier to understand and maintain the code.
7. Functions in C++ can be used to perform calculations, process data, manipulate strings, perform
input/output operations, and much more.
Types of functions:-There are two types of functions available in C++ programming.
1. Pre-defined Function (Built-in functions)
2. User-defined Function
1. Pre-defined Function
A predefined function in C++ refers to a function that is already defined in the C++ programming language and can
be used directly without needing to be declared or implemented again. C++ provide many built-in functions to
perform such as mathematical calculations, string manipulations, input/output operations, and memory
management useful operations. They are included in standard C++ libraries and can be called by their respective
function names. Predefined functions help in simplifying the coding process and enable programmers to
accomplish various tasks efficiently. C++ has around 32,000 inbuilt functions stored. The pre-defined function is
also known as In-built/derived/standard library function. You can easily call them without defining them as
they are already defined.
Example
strcmp(), strcpy(),
printf(), cin(). cout(),
scanf(),Sqrt() etc.
User-defined Function
A user-defined function in C++ is a function that is created by the user rather than being
built-in into the programming language. It allows the user to define their own functions with
specific functionality, which can be called and executed within the C++ program. User-
defined functions provide the ability to write modular and reusable code, enhancing the
overall structure and organization of the program. It increases the scope and functionality,
and reusability it can define and use any function when a user wants.
A set of statement that explains what a function does is called function definition. A function
definition in the C++ programming language is a block of code that specifies the actions or
operations to be executed when the function is called. It includes the name of the function, the input
parameters (if any), the return type (if any), and the actual code that performs the desired actions.
Function definitions allow programmers to break down their code into modular and reusable
components, making it easier to organize and maintain large projects.
After main()function.
In separate file
The function definition consists of two parts.
1. Function Header
2. Function Body
1. Function header :- the first line of function definition is known as function header. It is similar to
function prototype. The only difference is that it is not terminated with semicolon. The number of
parameters and sequence of parameters in function header and function prototype must be same.
2. Function Body :- the set of statements which are executed inside the function is known as
function body. The function body of function appears after the function declaration and the
statements are written in curly braces {}.
Function calling in C++
The statement that activates a function is known as function call. To call a function use the function
name followed by () parenthesis and ; terminator. Function calling in C++ refers to the process of
invoking or executing a function within a C++ program. When a function is called, the program
transfers control to that function, which performs a specific task or computation. The calling function
passes arguments or parameters to the called function, if required. After the called function finishes its
execution, the control returns back to the calling function, allowing it to continue from where it left
off. A function call is a fundamental concept in C++ programming and is used to organize code into
modular and reusable components.
The following steps take place when a function is called .
The control moves to the function that is called .
All statements in the function body are executed.
The control returns back to the calling function.
When the control returns back to the calling function the remaining statements in the calling function
are executed.
Example of function declaration, definition, calling
#include<iostream>
#include<conio.h>
Using namespace std;
void fun() // function header
{
Cout<<“ c programming in function”;
}
void main()
{
clrscr();
fun(); // function calling
getch();
}
Note:- If we are defining before main function we are not required to function prototype. If
we are defining after main function or any other separate file we are required to declared
function (function prototype).
Return type
A function can return single value. The return type of a function in the C++ programming
language determines the type of data that the function will return when it is executed. So, if
the function return type is int, then the function return value can be only integers. We can’t
return float or other data types. If the function return type is void, then the function returns
no value or expression.
Return value
In the C++ programming language, the return value refers to the value that a function sends
back to the caller after it has finished executing. It is specified in the function’s declaration
and can be of any valid data type in C++. When a function returns a value, it can be
assigned to a variable or used directly in expressions within the calling code. The return
value is a way for functions to provide the result or outcome of their execution to the rest of
the program.
The calling function can use the returned value in the following ways.
1. Assignment statement
2. Arithmetic expression
3. Output statement
Function Name
In C++ programming, a function name is a unique identifier that is used to refer to a
specific block of code that performs a specific task. It is important to choose descriptive and
meaningful names for functions to enhance code readability and maintainability.
Parameters
Parameters in C++ functions are values that are passed into the function when it is called.
They allow the function to perform specific operations based on the values provided.
Parameters are specified within the parentheses of a function declaration and can have
different data types, such as int, float, char, etc. When the function is called, the actual
values passed into the parameters are called arguments. The function can then use these
arguments to perform its intended tasks.
Types of Parameters
Parameters are divided into two types,
Actual Parameters
Formal Parameters
Actual Parameters
Actual parameters in C++ refer to the values that are passed to a function when it is called. These
values are provided by the caller of the function and are used by the function to perform its tasks. The
actual parameters are passed to the function through its arguments, which are specified in the
function’s declaration. By using actual parameters, programmers can pass information between
different parts of their program and perform various operations. Overall, actual parameters play a
crucial role in C++ programming by enabling the passing of data to functions.
Formal Parameters
Formal parameters in C++ refer to the variables that are declared in the function definition. They
receive values from the actual parameters or arguments that are passed when the function is called.
The formal parameters act as placeholders for these values within the function body. They allow data
to be passed into functions and enable the function to perform operations on that data. The scope of
formal parameters is limited to the function where they are declared, ensuring encapsulation and
preventing conflicts with variables outside the function.
Calling a Function:- Functions are called by their names. If the function is without argument, it can be
called directly using its name. But for functions with arguments, we have two ways to call them,
1. Call by Value
2. Call by Reference
Call by Value:- In this calling technique we pass the values of arguments which are stored or copied into the
formal parameters of functions. Hence, the original values are unchanged only the parameters inside function
changes. In this case the actual variable x is not changed, because we pass argument by value, hence a copy of x
is passed, which is changed, and that copied value is destroyed as the function ends(goes out of scope). So, the
variable x inside main() still has a value 10.
int main()
{
int x = 10;
calc(x);
printf("%d", x);
}
void calc(int x)
{
x = x + 10 ;
}
Object-A material thing that can be seen and touched. An object is a collection of data and functions. When a
class is defined no memory is allocated but when object is created memory is allocated. To use the data and
access functions defined in class ,you need to create object. In OOP program interacts with objects just like we
interact with object in our real life. The set of all functions of an object represents the behaviour of the object.
The fundamental idea behind object-oriented approach is to combine both data and function into a single unit
and these units are called objects. Two things are associated with object. 1. properties 2. Functions
1. Properties :are the characteristics of an object.
2. Functions :are the actions that can be performed by an object.
For example 1. car is a object -Properties of car are Colour, Model, Engine power, Price.
Functions of car are Start, Stop, Accelerate , Reverse.
For example 2. men is a object-Properties of Men are Name, Age, Height, Weight.
Functions of Men Run, Weep, Sleep, Eat, Drink
Class:-A class is like a blueprint for an object. Which holds the its own data members and member functions.
which can be accessed and used by creating an instance of that class. The variables inside class definition are
called as data members and the functions are called member functions.
1. Class name must start with an uppercase letter(Although this is not mandatory). If class name is made of
more than one word, then first letter of each word must be in uppercase.
2. Classes contain, data members and member functions, and the access of these data members and variable
depends on the access specifiers (discussed in next section).
3. Class's member functions can be defined inside the class definition or outside the class definition.
4. Class in C++ are similar to structures in C, the only difference being, class defaults to private access control,
where as structure defaults to public.
5. All the features of OOPS, revolve around classes in C++. Inheritance, Encapsulation, Abstraction etc.
6. Objects of class holds separate copies of data members. We can create as many objects of a class as we need.
7. Classes do posses more characteristics, like we can create abstract classes, immutable classes, all this we will
study later.
Access specifier in C++
Accessing a data member depends solely on the access control of that data member. If its public, then
the data member can be easily accessed using the direct member access (.) operator with the object of
that class.
If, the data member is defined as private or protected, then we cannot access the data variables
directly. Then we will have to create special public member functions to access, use or initialize the
private and protected data members. These member functions are also
called Accessors and Mutator methods or getter and setter functions.
Accessing Public Data Members:-Following is an example to show you how to initialize and use
the public data members using the dot (.) operator and the respective object of class.
class Student{
public:
int rollno;
string name;
};
int main()
{
Student A;
Student B;
A.rollno=1;
A.name="Adam";
B.rollno=2;
B.name=“thapa";
cout <<"Name and Roll no of A is: "<< A.name << "-" << A.rollno;
cout <<"Name and Roll no of B is: "<< B.name << "-" << B.rollno;
}
Accessing Private Data Members
To access, use and initialize the private data member you need to create getter and setter functions, to
get and set the value of the data member.
The setter function will set the value passed as argument to the private data member, and the getter
function will return the value of the private data member to be used. Both getter and setter function
must be defined public.
class Student{
private:
int rollno;
public:
int getRollno()
{
return rollno;
}
void setRollno(int i) {
rollno=i;
}};
int main(){
Student A;
A.rollono=1; //Compile time error
cout<< A.rollno; //Compile time error
A.setRollno(1); //Rollno initialized to 1
cout<< A.getRollno(); //Output will be 1
}
Accessing Protected Data Members
Protected data members, can be accessed directly using dot (.) operator inside the subclass of the
current class, for non-subclass we will have to follow the steps same as to access private data
member.
Member Functions of Classes in C++
Member functions are the functions, which have their declaration inside the class definition and
works on the data members of the class. The definition of member functions can be inside or outside
the definition of class.
If the member function is defined inside the class definition it can be defined directly, but if it's
defined outside the class, then we have to use the scope resolution :: operator along with class name
along with function name. class.
The main function for both the function definition will be same. Inside main() we will create object
of class, and will call the member function using dot . operator.
If we define the function inside class then we don't not need to declare it first, we can directly define the
function.
class Cube
{
public:
int side;
int getVolume()
{
return side*side*side; //returns volume of cube
}
};
But if we plan to define the member function outside the class definition then we must declare the
function inside class definition and then define it outside.
class Cube
{
public:
int side;
int getVolume();
}
int Cube :: getVolume() // member function defined outside class definition
{
return side*side*side;
}
Calling Class Member Function in C++:-Similar to accessing a data member in the class, we can also access
the public member functions through the class object using the dot operator (.).
Below we have a simple code example, where we are creating an object of the class Cube and calling the
member function getVolume():
int main()
{
Cube C1;
C1.side = 4; // setting side value
cout<< "Volume of cube C1 = "<< C1.getVolume();
}