[go: up one dir, main page]

0% found this document useful (0 votes)
71 views30 pages

Unit 2

Static data members and static member functions allow classes to maintain global state independent of any object instances. A static member exists only once per class, rather than each object having its own copy. Static members can be accessed via the class name without needing an object. Constructors and destructors allow initialization and cleanup of objects when they are created and destroyed.

Uploaded by

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

Unit 2

Static data members and static member functions allow classes to maintain global state independent of any object instances. A static member exists only once per class, rather than each object having its own copy. Static members can be accessed via the class name without needing an object. Constructors and destructors allow initialization and cleanup of objects when they are created and destroyed.

Uploaded by

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

Que1. What are static data members?

Explain difference between static


data members and non static data members. Also explain static
member function.

 A static member of a class can be static


 Static member variable is similar to c static variable.
 It is initialized to zero when the first object of the class is created.
 No other initialization is permitted.
 Static variable are used to maintain values common to the entire
class.
 We can define static variable outside the class also.
 While defining a static variable, some initial value can also be
assigned to the variable.
 Syntax: data_type class_name :: static_variable name[=initial
value]

Example: class myclass

Public:

Int x;

Static int count;

//default constructor

Myclass ()

Count++

}
};

Int myclass::count =0;

Int main ()

Cout<<”initial count =”<<myclass::count<<endl;

Myclass ob1, ob2;

Cout<<”count after 2 objects “<<myclass::count<<endl;

Return 0;

Difference between static and non-static data members

Basic of Static members Non-static member


difference
1.specification They are specified They are not specified
using the keyword using any keyword.
static
2.number of only one copy of static Only separate copy of
copies created data member is non-static data members
created for the entire is created for all the
class; no matter how objects.
many objects are
created
Variables of All objects share the all objects have their
objects same variable own copies of non static
data members.
Default values The default of static The default value of non
data member is zero static data member is
garbage, which is
unpredictable.
Life time Its life time is entire The life time depends on
program the scope of related
object.

Static member function

Member function of a class can also be declared as static. They have the
following properties:

1. A static member function can have access only other static


members which have declared in the class
2. A static member function can also be called by using its class
name.
That means, a static member function can also be called, if no
object of that class has been created,
The following understand the use of static members and
functions.

#include<iostream>

Using namespace std;

Class myclass

Private:

Int x;

Public:
Myclass() // default constructor

Count++;

Static int getcount()

Return count;

};

//initialization

Int myclass::count = 0;

Int main ()

Cout<<”initial count”<<myclass::getcount()<<endl;

Myclass obj1, obj2; // default constructor is called

Cout<<”count after 2 objects”<<myclass::getcount()<<endl;

Return 0;

Que2. Explain the use of constructor and destructors in c++ with the
help of an example.
Constructors

A constructor is a special kind of member function belonging to a class.

The basic feature of a constructor is a follows:

1) A constructor is invoking automatically whenever an object is


created.
2) A constructor always follows the category of public specifier.
3) A constructor can be non parameterized (default) as well as
parameterized.
4) A constructor does not require any return type not even a void
return type.
5) The name of the constructor is always the name of the class.

Defining a constructor

Syntax constructor_name ([argument list])

Example: distance (int f, float c)

feet = f;

inches = I;

Calling a constructor:

Distance obj = distance (5, 2.3)


Distance obj (5, 2.3)

Types of constructor:

a) default constructor

A constructor that accepts no parameters is called the default


constructor. We can define default constructor like this:

Distance ()

Feet =0;

Inches = 0.0f;

b) Parameterized constructor

A constructor which is defined to take one or more parameters, as


non-default constructor is known as parameterized constructor.

Distance (int f, float i)

Feet = f;

Inches = I;

c) Copy constructor
A copy constructor is used in the situation when we want to declare
an initialize an object from another object. A constructor takes the
reference of another object of the same class as a parameter.

Int main ()

Example obj1 (50);

Example obj2 (obj1);

Return 0;

d) Dynamic constructor

The constructor can also be used to allocate memory while creating


objects. The memory is created with the help of new operator.

Destructor

A destructor is a member function of a class that is executed


automatically when an object is destroyed.

Syntax: ~destructor_name ()

// function body

Example of all constructors

#include<iostream>
Using namespace std;

Class myclass2

Private:

Int x;

Public:

Myclass2 () //default constructor

X =10;

Myclass2 (int x) //parameterized constructor

X =x;

Myclass2 (myclass &o) //copy constructor

X = o.x;

Void show ()

{
Cout<<”\n value is “<<x;

~myclass2 () //destructor or de-constructor

Cout<<”object deleted”;

};

Int main ()

Myclass2 o1;

Int num;

Cout<<”enter the value”;

Cin>>num;

Myclass2 o2 (num); //dynamic memory allocation object

Myclass2 o3 (o1);

O1.show ();

O2.show ();

O3.show ();

Return 0;

}
Que3. What do you mean by specification of a class? Describe the
different access specifier in class.

Classes in c++

A class is a collection of objects of similar type.

Class is used to create user defined data types and behaves like built
in data types of programming language.

Class is a blueprint of an object that contains variables for storing


data and functions to perform operations on these data.

Data items in a class are called data members. The function within a
class is called member functions.[user defined class].

Class will not occupy any memory space.

Example:

Class name – fruit

Fruit mango, apple, orange:

A class must have a valid identifier name; it can begin with an


alphabetic character, the underscore, or the dollar sign.

Syntax for declaring a class:

The class body is declared within curly braces.

Class myclass {

Member variables;

………………………………..
Member functions ();

………………………………

}; // end class myclass

Program:

#include<iostream>

Using namespace std;

Class book

Private:

Int book_no;

Float price;

Public:

Void input ()

Cout<<”enter book number”;

Cin>>book_no;

Cout<<”enter the price”;

Cin>>price;

Void show ()
};

Void book :: show ()

Cout<<endl<<”book number ;”<<book_no

<<endl<<”price:”<<price;

Void main ()

Book obj;

Obj. input ();

Obj. show ();

Return 0;

Difference between private, public, and protected specifier

Private public Protected


Private members of a Public members of a It is similar to the
class can be class can be private but members
accessible only in the accessible from of a class are also
class in which it is anywhere within the accessible by class
declared & by friend program derived from that
function. class in which
members are
declared.
It can be used It can be used It is mainly used in
without inheritance. without inheritance inheritance.
Private keyword is Public keyword is Protected.
used to declare used to define public
private member of a members
class

Modifier Class Derived Outside Friend


function class function function
Private    
Public    
Protected    

Que4. What are read only objects? What is the role of constructor in
creating such objects? How can you create and destroy objects
dynamically? Explain with an example.

Ans. The dynamic initialization means that the initial value may be
provided during run time. Even class objects can be initialized
dynamically i.e. using the value which are provided at run time.

Example:

Class factorial

Private:

Int n;

Public:
Factorial (int number)

N = number;

Void display ()

Int fact =1;

If (n==0)

Cout<<”\n factorial =1”;

Else

For (int i=0;i<=n;i++)

Fact = fact *I;

Cout<<”\n factorial =”<<fact;

};

Int main ()

Int x;
Cout<<”enter the number to find the factorial”;

Cin>>x;

Factorial. Obj (x);

Obj. Display ();

Return 0;

Read-only objects:

Objects declared constant have a modified type whose value cannot


be changed; they are read only. For built in types declared as const,
this means that once initialized the compiler refuses.

Creating and destroying object dynamically

The new operator can be used to create objects of any type and its
general form is:

Pointer-variable = new data-type

To release memory space we use delete operator, the general form


is:

Delete pointer-variable;

For free to dynamically allocated memory

Delete [size] pointer-variable;

Example for using new and delete operator with dynamic


allocation.
#include<iostream>

#include<cstring>

Using namespace std;

Int main ()

Int num;

Cout<<”enter total number of students”;

Cin>>num;

Float *ptr;

Ptr = new float [num];

Cout<<”enter gpa of students”<<endl;

For (int i=0;i<num;i++)

Cout<<”student”<<i+1<<” “;

Cin>>*(ptr+i);

Cout<<”\n displaying gpa of students”<<endl;

For (int i=0;i<num;i++)

Cout<<”student”<<i+1<<” “<<*(ptr+i)<<endl;
}

Delete [] ptr;

Retrun 0;

Que. Data types in c++ can be classified under various categories.


Depict these in a diagram and discuss briefly.

Ans. A data types is a finite set of values along with set of rules for
permissible operations.

Categories of data type:

Show in figure, two broad categories of data types are- primitive and
non-primitive. Primitive data types have further two categories –
numeric and non numeric. Numeric data types have further two
categories –integers and floating point. Character data types comes
under non-numeric category. Classes and array are two non
primitive (i.e. derived data types).

DATA TYPES IN C++

PREMITIVE NON-PREMITIVE
ARRAYS

BUILT-IN
NUMERIC NON-NUMERIC
Void- to specify the return type of the function

To endiagte any empty argument list

Integer – declaration type – int


CHARACTER
Format specifier - %d, %i
INTEGER FLOATING
Memory POINT
space- 2 bytes

Short, long, signed, and unsigned

Range = -32768 to 32767

Character- declaration type – char

Format specifier - %c

Memory space = 1 byte

Short, long, signed and unsigned

Range = 128 to 127


Floating point- declaration type – float

Format specifier- %f

Memory space = 4 bytes

Range = 3.4E – 38 to 3.4E +38

Double – 8 byte and long double (very large double) = 10


byte

User defined data types

Structure, union  c class

Enumerated data type

 It helps to attach names to numbers


Even keyword is used
In c – enum – enumerates a list of word by assigning values
0, 1, 2---------with them

In c++ the tag names become new type names


Example enum shape {circle, square, triangle}

Enum color {red, blue, green}

Shape and color  new type names

BY using new type names we can declare new variables.


Example: shape ellipse;

Color background;
In c programming enum is type of int but in c++, ach of different type.
C++ does not permit an int value to be automatically connected to an
enum.

Example: color background = blue;

Color background = 7;

Color background = (color) 7;

Enum value can use in place of int value.


Example: int c = red;// color type promoted to int

Enumerators are by default assigned with the value from 0 to n.


Example – enum color {red, blue, green}.

Que. What is friend function? How it is different from a member


function?

Ans. A friend function is a special function in c++ has an important


feature to access private and protected data of a class. A friend
function is used for accessing non public members of a class. The friend
function is written as any other normal function.

Why do we need friend function?

In special case when class’s private data needs to be accessed directly
without using object of that class.

Friend function is performing operator overloading.


Example: // c++ program to demonstrate the working of friend function.

#include<iostream>
Using namespace std;

Class distance

Private:

Int meters;

Public:

Distance ()

Meters = 0;

Void displaydata ()

Cout<<”meter value is =”<<mater;

Friend void addvalue (distance &d)

};

Void addvalue (distance &d)

d.meters = d.meters +5;

}
Int main ()

Distance d1;

D1.displaydata ();

Return 0;

OUTPUT

Meter value = 0

Que. What is function in c++? How will you define and call a function?
Explain with an example.

Ans. A function is a self contained program structure that is used to


perform a specific task.

Any c++ program contains atleast one function. If a program contains


only one function. It must be main () function. There is no limit on the
member function that are present in c++ program.

Some functions are already defined in c++ library. They are called as
library functions. These library functions can be easily be used in c++
programs, another that user can create some new functions also, which
are called user defined functions.

There are three things related with c++ program.

Its definition

Its declaration
And its calling

Void show () /*function declaration

Main()

……….

Show()/*function call*/

Void show() /*function definition */

……….//function body

The function definition: general syntax to define a function is r

Return type function_name (parameter list)

// the body of method

/* program to calculate the volume using a function having three


arguments and having a return type */

#include<iostream>
Double volume (double w, double h, double d)// function declaration or
prototype

Void main () //definition of main function

Double width, height, depth, vol;

Width = 5.6;

Height = 3.4;

Depth = 2.3;

Vol = volume (width, height, depth); //function calling

Cout<<”the volume is =”<<vol;

Double volume (double w, double h, double d) //definition of function


volume ()

Double v;

V = w*h*d;

Return v;

Output = the volume is: 43.792

Calling the function:


A function is called by its specifying its name within an expression. The
call is terminated by semicolon (;).

You might also like