Btech C++unit 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Introduction to c++

C++ is a middle-level programming 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 versions of UNIX.
C++ is an object-oriented programming language which gives a clear
structure to programs and allows code to be reused, lowering
development costs.

C++ is portable and can be used to develop applications that can be


adapted to multiple platforms.C++ is fun and easy to learn!

As C++ is close to C# and Java, it makes it easy for programmers to


switch to C++ or vice versa.

Header files in C++

header files contain the set of predefined standard library functions.


You request to use a header file in your program by including it with the
C preprocessing directive “#include”. All the header file have a ‘.h’ an
extension. A header file contains:

Function definitions

Data type definitions

Macros

It offers the above features by importing them into the program with
the help of a preprocessor directive “#include”. These preprocessor
directives are used for instructing compiler that these files need to be
processed before compilation. There are of 2 types of header file:
Pre-existing header files: Files which are already available in C/C++
compiler we just need to import them.

User-defined header files: These files are defined by the user and can
be imported using “#include”.

Syntax:

#include <filename.h>

or

#include "filename.h"

List of header files on c++

1. #include<stdio.h>

2.#include<string.h> (String header)

3. #include<conio.h> (Console input-output header)

4. #include<stdlib.h> (Standard library header)

5. #include<math.h> (Math header )

6. #include<ctype.h>(Character type header)

7. #include<time.h>(Time header)

8.#inlcude<iostream> (Input Output Stream) – Used as a stream of


Input and Output.

9.#include<iomanip.h> (Input-Output Manipulation) – Used to access


set() and setprecision().
10.#include<fstream.h> (File stream) – Used to control the data to read
from a file as an input and data to write into the file as an output.

Application of c++ programming language

1. Operating Systems

C++ is a fast and strongly-typed programming language which makes it


an ideal choice for developing operating systems.

2. Games

Since C++ is closer to hardware, game development companies use it as


their primary choice to develop gaming systems.

3. GUI Based Applications

C++ is also used to develop GUI-based and desktop applications.

4.Banking Applications

Since banking applications require concurrency, multi-threading,


concurrency, and high

performance, C++ is the default choice of programming language.


Infosys Finacle is a popular banking application developed using C++.

Data hiding

Data hiding means hiding the internal data within the class to prevent
its direct access from outside the class.

Example: We can understand data hiding with an example. Suppose we


declared an Account class with a data member balance inside it. Here,
the account balance is sensitive information. We may allow someone to
check the account balance but won't allow altering the balance
attribute. So, by declaring the balance attribute private, we can restrict
the access to balance from an outside application.

C++ Polymorphism

The term "Polymorphism" is the combination of "poly" + "morphs"


which means many forms. It is a greek word.

Real Life Example Of Polymorphism

Let's consider a real-life example of polymorphism. A lady behaves like


a teacher in a classroom, mother or daughter in a home and customer
in a market. Here, a single person is behaving differently according to
the situations.

Another example of polymorohisn is :

Consider '+' operator, if we apply + operator on a numbers , it will


return the sum of numbers but if we apply this + operator on string it
will concatenate the string.

Dynamic binding

Binding refers to the linking of a particular procedure call to the code to


be executed in response to the call. Dynamic binding means that the
code associated with a given procedure call is not known until the time
of the call at run time.

Data members are the data variables and member functions are the
functions used to manipulate these variables and together these data
members and member functions defines the properties and behavior of
the objects in a Class.
In the example of class Car, the data member will be speed limit,
mileage etc and member functions can be apply brakes, increase speed
etc.

An Object is an instance of a Class. When a class is defined, no memory


is allocated but when it is instantiated (i.e. an object is created)
memory is allocated.

Example - class Abc


{

Int a; // data member

Simple c++ program

#include <iostream>

int main() {

cout << "Hello World!";

return 0;

Example explained

Line 1: #include <iostream> is a header file library that lets us work with
input and output objects, such as cout (used in line 5). Header files add
functionality to C++ programs.

Line 2: Another thing that always appear in a C++ program, is int main().
This is called a function. Any code inside its curly brackets {} will be
executed.
Line 3: cout (pronounced "C -out") is an object used together with the
insertion operator (<<) to output/print text. In our example it will
output "Hello World".

Note: Every C++ statement ends with a semicolon ;.

Line 4: return 0 ends the main function.

Pure Virtual Functions and Abstract Classes in C++

Sometimes implementation of all function cannot be provided in a base


class because we don’t know the implementation. Such a class is called
abstract class. For example, let Shape be a base class. We cannot
provide implementation of function draw() in Shape, but we know
every derived class must have implementation of draw(). Similarly an
Animal class doesn’t have implementation of move() (assuming that all
animals move), but all animals must know how to move. We cannot
create objects of abstract classes.

A pure virtual function (or abstract function) in C++ is a virtual function


for which we can have implementation, But we must override that
function in the derived class, otherwise the derived class will also
become abstract class .

A pure virtual function is declared by assigning 0 in declaration. See the


following example.

// An abstract class

class Test

{
// Data members of class

public:

// Pure Virtual Function

virtual void show() = 0;

/* Other members */

};

A complete example:

A pure virtual function is implemented by classes which are derived


from a Abstract class. Following is a simple example to demonstrate the
same.

#include<iostream>

using namespace std;

class Base

int x;

public:

virtual void fun() = 0;

int getX() { return x; }

};

// This class inherits from Base and implements fun()


class Derived: public Base

int y;

public:

void fun() { cout << "fun() called"; }

};

int main(void)

Derived d;

d.fun();

return 0;

Output:

fun() called

Access specifier

Access Modifiers or Access Specifiers in a class are used to assign the


accessibility to the class members, i.e., they set some restrictions on
the class members so that they can’t be directly accessed by the
outside functions.

There are 3 types of access modifiers available in C++:

Public
Private

Protected

Note: If we do not specify any access modifiers for the members inside
the class, then by default the access modifier for the members will be
Private.

Let us now look at each one of these access modifiers in detail:

1. Public: All the class members declared under the public specifier will
be available to everyone. The data members and member functions
declared as public can be accessed by other classes and functions too.
The public members of a class can be accessed from anywhere in the
program using the direct member access operator (.) with the object of
that class.

Example:

// C++ program to demonstrate public

// access modifier

#include<iostream>

using namespace std;

// class definition

class Circle

public:

double radius;
double compute_area()

return 3.14*radius*radius;

};

// main function

int main()

Circle obj;

// accessing public datamember outside class

obj.radius = 5.5;

cout << "Radius is: " << obj.radius << "\n";

cout << "Area is: " << obj.compute_area();

return 0;

Output:

Radius is: 5.5

Area is: 94.985


In the above program, the data member radius is declared as public so
it could be accessed outside the class and thus was allowed access from
inside main().

2. Private: The class members declared as private can be accessed only


by the member functions inside the class. They are not allowed to be
accessed directly by any object or function outside the class. Only the
member functions or the friend functions are allowed to access the
private data members of the class.

Example:

// C++ program to demonstrate private

// access modifier

#include<iostream>

using namespace std;

class Circle

// private data member

private:

double radius;

// public member function

public:

double compute_area()
{ // member function can access private

// data member radius

return 3.14*radius*radius;

};

// main function

int main()

// creating object of the class

Circle obj;

// trying to access private data member

// directly outside the class

obj.radius = 1.5;

cout << "Area is:" << obj.compute_area();

return 0;

The output of the above program is a compile time error because we


are not allowed to access the private data members of a class directly
from outside the class. Yet an access to obj.radius is attempted, but
radius being a private data member, we obtained the above
compilation error.
However, we can access the private data members of a class indirectly
using the public member functions of the class.

Protected: The protected access modifier is similar to the private access


modifier in the sense that it can’t be accessed outside of its class unless
with the help of a friend class. The difference is that the class members
declared as Protected can be accessed by any subclass (derived class) of
that class as well.

Note: This access through inheritance can alter the access modifier of
the elements of base class in derived class depending on the mode of
Inheritance.

Example:

// C++ program to demonstrate

// protected access modifier

#include <bits/stdc++.h>

using namespace std;

// base class

class Parent

// protected data members

protected:

int id_protected;

};
// sub class or derived class from public base class

class Child : public Parent

public:

void setId(int id)

// Child class is able to access the inherited

// protected data members of base class

id_protected = id;

void displayId()

{ cout << "id_protected is: " << id_protected << endl;

};

// main function

int main() {

Child obj1;

// member function of the derived class can

// access the protected data members of the base class

obj1.setId(81);
obj1.displayId();

return 0;

Output:

id_protected is: 81

Accessing data members and member functions: The data members


and member functions of class can be accessed using the dot(‘.’)
operator with the object. For example if the name of object is obj and
you want to access the member function with the name printName()
then you will have to write obj.printName() .

Accessing Data Members

The public data members are also accessed in the same way given
however the private data members are not allowed to be accessed
directly by the object. Accessing a data member depends solely on the
access control of that data member.

This access control is given by Access modifiers in C++. There are three
access modifiers : public, private and protected.

// C++ program to demonstrate

// accessing of data members

#include <iostream>

using namespace std;

class Geeks
{

// Access specifier

public:

// Data Members

string geekname;

// Member Functions()

void printname() {

cout << "Geekname is: " << geekname;

};

int main() {

// Declare an object of class geeks

Geeks obj1;

// accessing data member

obj1.geekname = "Abhi";

// accessing member function

obj1.printname();

return 0;

Output:
Geekname is: Abhi

What is a structure?

A structure is a user-defined data type in C/C++. A structure creates a


data type that can be used to group items of possibly different types
into a single type.

Structures in C++

We often come around situations where we need to store a group of


data whether of similar data types or non-similar data types. We have
seen Arrays in C++ which are used to store set of data of similar data
types at contiguous memory locations.

Unlike Arrays, Structures in C++ are user defined data types which are
used to store group of items of non-similar data types.

The ‘struct’ keyword is used to create a structure. The general syntax to


create a structure is as shown below:

struct structureName{

member1;

member2;

member3;

memberN;
};

How to declare structure variables?

A structure variable can either be declared with structure declaration or


as a separate declaration like basic types.

// A variable declaration with structure declaration.

struct Point

int x, y;

} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types

struct Point

int x, y;

};

int main()

struct Point p1; // The variable p1 is declared like a normal variable

Structures in C++ can contain two types of members:

Data Member: These members are normal C++ variables. We can


create a structure with variables of different data types in C++.
Member Functions: These members are normal C++ functions. Along
with variables, we can also include functions inside a structure
declaration.

Example:

// Data Members

int roll;

int age;

int marks;

// Member Functions

void printDetails()

cout<<"Roll = "<<roll<<"\n";

cout<<"Age = "<<age<<"\n";

cout<<"Marks = "<<marks;

In the above structure, the data members are three integer variables to
store roll number, age and marks of any student and the member
function is printDetails() which is printing all of the above details of any
student.

A structure variable can either be declared with structure declaration or


as a separate declaration like basic types.
Structure members cannot be initialized with declaration. For example
the following C program fails in compilation.

struct Point

int x = 0; // COMPILER ERROR: cannot initialize members here

int y = 0; // COMPILER ERROR: cannot initialize members here

};

The reason for above error is simple, when a datatype is declared, no


memory is allocated for it. Memory is allocated only when variables are
created.

Structure members can be initialized with declaration in C++. For


Example the following C++ program Executes Successfully without
throwing any Error.

// In C++ We can Initialize the Variables with Declaration in Structure.

#include <iostream>

using namespace std;

struct Point {

int x = 0; // It is Considered as Default Arguments and no Error is


Raised

int y = 1;

};
int main()

struct Point p1;

// Accessing members of point p1

// No value is Initialized then the default value is considered. ie x=0 and


y=1;

cout << "x = " << p1.x << ", y = " << p1.y<<endl;

// Initializing the value of y = 20;

p1.y = 20;

cout << "x = " << p1.x << ", y = " << p1.y;

return 0;

// This code is contributed by Samyak Jain

x=0, y=1

x=0, y=20

Structure members can be initialized using curly braces ‘{}’. For


example, following is a valid initialization.

struct Point {

int x, y;

};
int main()

// A valid initialization. member x gets value 0 and y

// gets value 1. The order of declaration is followed.

struct Point p1 = { 0, 1 };

How to access structure elements?

Structure members are accessed using dot (.) operator.

#include <iostream>

using namespace std;

struct Point {

int x, y;

};

int main()

struct Point p1;

P1. x=10;

// Accessing members of point p1

p1.y= 20;
cout << "x = " << p1.x << ", y = " << p1.y;

return 0;

Output

x = 10, y = 20

C++ Overloading (Function and Operator)


If we create two or more members having the same name but different in number
or type of parameter, it is known as C++ overloading. In C++, we can overload:
 function,
 constructors, and

C++ Function Overloading


Function Overloading is defined as the process of having two or more function
with the same name, but different in parameters is known as function overloading
in C++. In function overloading, the function is redefined by using either different
types of arguments or a different number of arguments. It is only through these
differences compiler can differentiate between the functions.
The advantage of Function overloading is that it increases the readability of the
program because you don't need to use different names for the same action.

C++ Function Overloading Example


#include<iostream>
using namespace std;
class abc
{
int a.b.c;
public: void add()
{
a=10;
b=20;
c=a+b;
cout<<”sum=”<<c;
}
void add(int a,int b)
{
c=a+b;
cout<<”sum=”<<c;
}
void add(int a,float b)
{
c=a+b;
cout<<”sum=”<<c;
}
};
void main()
{
abc ob;
ob.add();
ob.add(4,6);
ob.add(45,9.8);
}


Output:

constant
As the name suggests the name constants are given to such variables or
values in C/C++ programming language which cannot be modified once
they are defined. They are fixed values in a program. There can be any
types of constants like integer, float, octal, hexadecimal, character
constants, etc.

Defining Constants:
In C/C++ program we can define constants in two ways as shown below:

1. Using #define preprocessor directive


2. Using a const keyword

Literals: The values assigned to each constant variables are referred to as


the literals. Generally, both terms, constants and literals are used
interchangeably. For eg, “const int = 5;“, is a constant expression and the
value 5 is referred to as constant integer literal.

1. Using #define preprocessor directive: This directive is used to


declare an alias name for existing variable or any value. We can use this to
declare a constant as shown below:
#define identifierName value

identifierName: It is the name given to constant.


value: This refers to any value assigned to identifierName.

2. using a const keyword: Using const keyword to define constants is
as simple as defining variables, the difference is you will have to precede
the definition with a const keyword.

Syntax-const data_type variablename=value;

Where const is a keyword

Data type is the type of data stored by variable

Variable name is the name of variable

Example-const int a=10;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy