Sunteți pe pagina 1din 29

ID NO-18CE082

ASSIGNMENT:-1

NAME :PATEL MEET TEJASKUMAR


ID.NO :18CE082
SUBJECT :OBJECT ORIENTED
PROGRAMMING WITH C++
ID NO-18CE082

Introduction to Object Oriented concepts and Design & Principles of object-oriented Programming

OUESTION 1:-

Define Object-oriented programming and Explain feature of Object oriented Programming. How
it is different than procedure oriented programming.

ANSWER:-

Object-oriented programming (OOP) refers to a type of computer programming (software design) in


which programmers define not only the data type of a data structure, but also the types of operations (functions)
that can be applied to the data structure.
In this way, the data structure becomes an object that includes both data and functions. In addition,
programmers can create relationships between one object and another. For example, objects can inherit
characteristics from other objects.
Feature:-
Abstraction: The process of picking out (abstracting) common features of objects and procedures.
Class: A category of objects. The class defines all the common properties of the different objects that
belong to it.
Encapsulation: The process of combining elements to create a new entity. A procedure is a type of
encapsulation because it combines a series of computer instructions.
Information hiding: The process of hiding details of an object or function. Information hiding is a powerful
programming technique because it reduces complexity.
Inheritance: a feature that represents the "is a" relationship between different classes.
Interface: the languages and codes that the applications use to communicate with each other and with the
hardware.
Messaging: Message passing is a form of communication used in parallel programming and object-oriented
programming.
Object: a self-contained entity that consists of both data and procedures to manipulate the data.
Polymorphism: A programming language's ability to process objects differently depending on their data
type or class.
Procedure: a section of a program that performs a specific task.

Both are programming processes whereas OOP stands for “Object Oriented Programming” and POP stands
for “Procedure Oriented Programming”. Both are programming languages that use high-
level programming to solve a problem but using different approaches.
ID NO-18CE082

OUESTION 2:-

Explain all major characteristics of Object Oriented Programming with real world Applications.

ANSWER:-

Here Are Some Applications Of Object Oriented Programming:-


1. Client-Server SystemsObject-oriented Client-Server Systems provide the IT infrastructure,
creating object-oriented Client-Server Internet (OCSI) applications. Here, infrastructure refers to
operating systems, networks, and hardware. OSCI consist of three major technologies:

 The Client Server


 Object Oriented Programming
 The Internet

2. Object Oriented Databases

They are also called Object Database Management Systems (ODBMS). These databases store objects
instead of data, such as real numbers and integers. Objects consist of the following:

Attributes: Attributes are data that defines the traits of an object. This data can be as simple as
integers and real numbers. It can also be a reference to a complex object.

Methods: They define the behavior and are also called functions or procedures.

3. Object Oriented Databases

These databases try to maintain a direct correspondence between the real-world and database objects
in order to let the object retain their identity and integrity. They can then be identified and operated
upon.

4. Real-Time System Design

Real time systems inherit complexities that makes difficult to build them. Object-oriented techniques
make it easier to handle those complexities. These techniques present ways of dealing with these
complexities by providing an integrated framework which includes schedulability analysis and
behavioral specifications.

5. Simulation And Modelling System

It’s difficult to model complex systems due to the varying specification of variables. These are
prevalent in medicine and in other areas of natural science, such as ecology, zoology, and agronomic
systems. Simulating complex systems requires modelling and understanding interactions explicitly.
Object-oriented Programming provides an alternative approach for simplifying these complex
modelling systems.

6. Hypertext And Hypermedia

OOP also helps in laying out a framework for Hypertext. Basically, hypertext is similar to regular text
as it can be stored, searched, and edited easily. The only difference is that hypertext is text with
pointers to other text as well.
ID NO-18CE082

Hypermedia, on the other hand, is a superset of hypertext. Documents having hypermedia, not only
contain links to other pieces of text and information, but also to numerous other forms of media,
ranging from images to sound.

7. Neural Networking And Parallel Programming

It addresses the problem of prediction and approximation of complex time-varying systems. Firstly,
the entire time-varying process is split into several time intervals or slots. Then, neural networks are
developed in a particular time interval to disperse the load of various networks. OOP simplifies the
entire process by simplifying the approximation and prediction ability of networks.

8. Office Automation Systems

These include formal as well as informal electronic systems primarily concerned with information
sharing and communication to and from people inside as well as outside the organization. Some
examples are:

 Email
 Word processing
 Web calendars
 Desktop publishing

9. CIM/CAD/CAM Systems

OOP can also be used in manufacturing and design applications as it allows people to reduce the effort
involved. For instance, it can be used while designing blueprints, flowcharts, etc. OOP makes it
possible for the designers and engineers to produce these flowcharts and blueprints accurately.

10. AI Expert Systems

These are computer applications which are developed to solve complex problems pertaining to a
specific domain, which is at a level far beyond the reach of a human brain.

It has the following characteristics:

 Reliable
 Highly responsive
 Understandable
 High-performance

ID NO-18CE082

Introduction of C++

OUESTION 3:-

Write down importance of using namespace. How we create and use user defined namespace?
Explain nesting user define namespace concepts with small example

ANSWER:-

Namespace is a feature added in C++ and not present in C. A namespace is a declarative region that provides a
scope to the identifiers (names of the types, function, variables etc) inside it. Multiple namespace blocks with the
same name are allowed. All declarations within those blocks are declared in the named scope.

Namespaces provide a method for preventing name conflicts in large projects.


Symbols declared inside a namespace block are placed in a named scope that prevents them from being mistaken
for identically-named symbols in other scopes.
Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in
the named scope.
Syntax

namespace ns_name { declarations } (1)

(since
inline namespace ns_name { declarations } (2)
C++11)

namespace { declarations } (3)

ns_name::name (4)

using namespace ns_name; (5)


ID NO-18CE082

using ns_name::name; (6)

namespace name = qualified-namespace ; (7)

namespace ns_name::inline(since (since


(8)
C++20)(optional) name { declarations } C++17)

Named namespace definition for the namespace ns_name.


Inline namespace definition for the namespace ns_name. Declarations inside ns_name will be visible in its
enclosing namespace.
Unnamed namespace definition. Its members have potential scope from their point of declaration to the end of the
translation unit, and have internal linkage.
Namespace names (along with class names) can appear on the left hand side of the scope resolution operator, as
part of qualified name lookup.
using-directive: From the point of view of unqualified name lookup of any name after a using-directive and until
the end of the scope in which it appears, every name from ns_name is visible as if it were declared in the nearest
enclosing namespace which contains both the using-directive and ns_name.
using-declaration: makes the symbol name from the namespace ns_name accessible for unqualified lookup as if
declared in the same class scope, block scope, or namespace as where this using-declaration appears.
namespace-alias-definition: makes name a synonym for another namespace: see namespace alias

nested namespace definition: namespace A::B::C { ... } is equivalent


to namespace A { namespace B { namespace C { ... } } }.

namespace A::B::inline C { ... } is equivalent to namespace A::B { inline namespace C { ... } }. inline may
appear in front of every namespace name except the first: namespace A::inline B::C {} is equivalent
to namespace A { inline namespace B { namespace C {} } }.

Example:-
// Here we can see that more than one variables
// are being used without reporting any error.
// That is because they are declared in the
// different namespaces and scopes.
#include <iostream>
using namespace std;
ID NO-18CE082

// Variable created inside namespace


namespace first
{
int val = 500;
}
// Global variable
int val = 100;
int main()
{
// Local variable
int val = 200;
// These variables can be accessed from
// outside the namespace using the scope
// operator ::
cout << first::val << '\n';
return 0;
}

OUESTION 4:-

What is extractions and insertion operator? write short note on structure of c++ program

ANSWER:-

C++ is able to input and output the built-in data types using the stream extraction operator >> and the
stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to
perform input and output for user-defined types like an object.
Programs are a sequence of instructions or statements. These statements form the structure of a C++ program.
C++ program structure is divided into various sections, namely, headers, class definition, member functions
definitions and main function.
ID NO-18CE082

Note that C++ provides the flexibility of writing a program with or without a class and its member functions
definitions. A simple C++ program (without a class) includes comments, headers, namespace, main() and
input/output statements.
Comments are a vital element of a program that is used to increase the readability of a program and to describe
its functioning. Comments are not executable statements and hence, do not increase the size of a file.

Tokens and Expressions & Control Structure

OUESTION 5:-

Explain C++ data types and operators in C++ in detail. If we use boolean data type in code then
which line must be needed if we want to write “true / flase” instead of “1 / 0”in output screen?

ANSWER:-

Data types in C++ is mainly divided into two types:


1. Primitive Data Types: These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc. Primitive data types
available in C++ are:
 Integer
 Character
 Boolean
 Floating Point
 Double Floating Point
 Valueless or Void
ID NO-18CE082

 Wide Character
2. Abstract or user defined data type: These data types are defined by user itself. Like, defining a
class in C++ or a structure.
This article discusses primitive data types available in C++.
 Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of memory
space and ranges from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters. Keyword used for character data
type is char. Characters typically requires 1 byte of memory space and ranges from -128 to 127 or
0 to 255.
 Boolean: Boolean data type is used for storing boolean or logical values. A boolean variable can
store either true or false. Keyword used for boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single precision floating point values
or decimal values. Keyword used for floating point data type is float. Float variables typically
requires 4 byte of memory space.
 Double Floating Point: Double Floating Point data type is used for storing double precision
floating point values or decimal values. Keyword used for double floating point data type
is double. Double variables typically requires 8 byte of memory space.
 void: Void means without any value. void datatype represents a valueless entity. Void data type is
used for those function which does not returns a value.
 Wide Character: Wide character data type is also a character data type but this data type has size
greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2 or 4 bytes long.
Datatype Modifiers: As the name implies, datatype modifiers are used with the built-in data types to
modify the length of data that a particular data type can hold. Data type modifiers available in C++ are:
 Signed
 Unsigned
 Short
 Long

OPERATOR DESCRIPTION ASSOCIATIVITY

() Parentheses (function call) left-to-right

[] Brackets (array subscript)

. Member selection via object name

-> Member selection via pointer

++/– Postfix increment/decrement

++/– Prefix increment/decrement right-to-left

+/- Unary plus/minus


ID NO-18CE082

!~ Logical negation/bitwise complement

(type) Cast (convert value to temporary value of type)

* Dereference

& Address (of operand)

sizeof Determine size in bytes on this implementation

*,/,% Multiplication/division/modulus left-to-right

+/- Addition/subtraction left-to-right

<< , >> Bitwise shift left, Bitwise shift right left-to-right

< , <= Relational less than/less than or equal to left-to-right

> , >= Relational greater than/greater than or equal to left-to-right

== , != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left


ID NO-18CE082

= Assignment right-to-left

+= , -= Addition/subtraction assignment

*= , /= Multiplication/division assignment

%= , &= Modulus/bitwise AND assignment

^= , |= Bitwise exclusive/inclusive OR assignment

<>= Bitwise shift left/right assignment

, expression separator left-to-right

Boolean variables are variables that can have only two possible values: true (1), and false (0). To declare a boolean
variable, we use the keyword bool.

1 bool b;

To initialize or assign a true or false value to a boolean variable, we use the keywords true and false.

1 bool b1 = true; // copy initialization


2 bool b2(false); // direct initialization
3 bool b3 { true }; // uniform initialization (C++11)
4 b3 = false; // assignment

Just as the unary minus operator (-) can be used to make an integer negative, the logical NOT operator (!) can be
used to flip a boolean value from true to false, or false to true:

1 bool b1 = !true; // b1 will have the value false


2 bool b2(!false); // b2 will have the value true

Boolean values are not actually stored in boolean variables as the words “true” or “false”. Instead, they are stored
as integers: true becomes the integer 1, and false becomes the integer 0. Similarly, when boolean values are
evaluated, they don’t actually evaluate to “true” or “false”. They evaluate to the integers 0 (false) or 1 (true).

OUESTION 6:-

What is scope resolution operator? what are the applications for it?

ANSWER:-
ID NO-18CE082

It is used to access an item that is outside the current scope. It is used for distinguishing class members and
defining class methods. A major application of the scope resolution operator is in the classes to identify
the class to which a member function belongs.

Sign:- ::

 It permits a program to reference an identifier in the global scope that has been hidden by another identifier
with the same name in the local scope.
 It is used to access an item that is outside the current scope.
 It is used for distinguishing class members and defining class methods.
 A major application of the scope resolution operator is in the classes to identify the class to which a
member function belongs.

OUESTION 7:-

Explain how to allocate and de-allocate memory dynamically in c++.

ANSWER:-

One of the coolest (and scariest!) features of C++ is that you can work directly with memory usage of a program.
As a programmer, you can go grab a chunk of memory from the operating system, use it, then free it up. But you
need to watch out for memory leaks.
When we use dynamic memory, we are using memory on the Heap (whereas local variables are allocated on
the Stack). Figure 1 depicts how the memory corresponds to code. Note that heap memory is also called free
memory.

Think of a memory leak in terms of an oil change on a car. If you don't tighten up all the bolts and seals, you will
leak oil. The same is true for memory in C++. If you set a side a bunch of memory for use, and never give it back,
and memory leaks out. If this goes on long enough, or the leaks are big enough, your engine (computer) is going
to seize (crash).
ID NO-18CE082

Keeping the warnings aside, let's walk through each of the C++ functions that are used for memory management.

C++ Memory Management Tools


There are a few functions that you can use to allocate, reallocate, and free up memory in C++.

Malloc()
The malloc() function is a carryover from C. You can still use it in C++ in order to allocate a block of memory
for your program's needs. In the rare event that the allocation fails, you will want to be sure you are able to catch
that error.
The syntax of malloc() is as follows:

1. void* malloc(size_t size);

Let's say you want to create a string for a user name and allocated 25 bytes for that name, the following code is
used:

1. char *user;
2. user = (char *) malloc(25);

The following is a working C++ program that uses malloc(). Note that we have included the cstdlib header file as
well. We also used the free() function. We'll talk about this later, but this is needed to help prevent an oil (memory)
leak.

1. #include <iostream>
2. #include <cstdlib>
3. #include <cstring>
4. using namespace std;
5. int main() {
6. char *user;
7. user = (char *) malloc(25);
8. strcpy(user, "Jane_Eyre");
9. cout << "User Name = " << user << " " << &user << endl;
10. free(user);
11. }

New
While malloc() will work in C++, there is a growing use of the new() function instead. Instead of malloc, we
could create a login name with the new function:

1. char *login = new char(50);

Then, when done, you use delete instead of free:

1. delete(login);

Realloc()
If you need to reallocate a memory block, you can use the realloc() function.

1. void* realloc (void* ptr, size_t size);


ID NO-18CE082

Where ptr is the pointer to the block of memory you already allocated. If that block doesn't exist, a new block is
created. Size is the memory size for the new block.
Add the following code before the line that calls the free() function:

1. //re-allocate
2. user = (char *) realloc(user, 50);
3. strcat(user, " Login Info");
4. cout << user << " " << &user << endl;

Free
The free() function frees up/releases the memory that you have allocated or reallocated. You have seen how we've
used free to tell C++ to relinquish the memory:

1. free(user);

Functions in C++

OUESTION 8:-

When do we need to use default arguments in a function? Discuss with small program.

ANSWER:-

In C++ programming, you can provide default values for function parameters.

The idea behind default argument is simple. If a function is called by passing argument/s, those arguments are
used by the function.

But if the argument/s are not passed while invoking a function then, the default values are used.

Default value/s are passed to argument/s in the function prototype.


ID NO-18CE082

Working of default arguments

Example: Default Argument

// C++ Program to demonstrate working of default argument

#include <iostream>
using namespace std;

void display(char = '*', int = 1);

int main()
{
cout << "No argument passed:\n";
display();

cout << "\nFirst argument passed:\n";


display('#');
ID NO-18CE082

cout << "\nBoth argument passed:\n";


display('$', 5);

return 0;
}

void display(char c, int n)


{
for(int i = 1; i <= n; ++i)
{
cout << c;
}
cout << endl;
}

Output

No argument passed:

*First argument passed:

Both argument passed:

$$$$$

In the above program, you can see the default value assigned to the arguments void display(char = '*', int = 1);.

At first, display() function is called without passing any arguments. In this case, display()function used both
default arguments c = * and n = 1.
ID NO-18CE082

Then, only the first argument is passed using the function second time. In this case, function does not use first
default value passed. It uses the actual parameter passed as the first argument c = # and takes default value n =
1 as its second argument.

When display() is invoked for the third time passing both arguments, default arguments are not used. So, the value
of c = $ and n = 5.

OUESTION 9:-

Explain different use of const keyword in C++.

ANSWER:-

A function becomes const when const keyword is used in function’s declaration. The idea of const functions is
not allow them to modify the object on which they are called. It is recommended practice to make as many
functions const as possible so that accidental changes to objects are avoided.
Following is a simple example of const function.
#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0) {value = v;}

// We get compiler error if we add a line like "value = 100;"


// in this function.
int getValue() const {return value;}
};

int main() {
Test t(20);
cout<<t.getValue();
return 0;
}

Output:
20
When a function is declared as const, it can be called on any type of object. Non-const functions can only be
called by non-const objects.
For example the following program has compiler errors.
#include<iostream>
using namespace std;

class Test {
int value;
public:
Test(int v = 0) {value = v;}
ID NO-18CE082

int getValue() {return value;}


};

int main() {
const Test t;
cout << t.getValue();
return 0;
}
Output:
passing 'const Test' as 'this' argument of 'int
Test::getValue()' discards qualifiers
ID NO-18CE082

Classes and objects

OUESTION 10:-

What is friend functions? what is the difference between friend function of a class and a member
function of a class?

ANSWER:-

Friend Class A friend class can access private and protected members of other class in which it is declared
as friend. It is sometimes useful to allow a particular class to access private members of other class. For example a
LinkedList class may be allowed to access private members of Node.

OUESTION 11:-

When do we declare a member of a class static? Why? Discuss static member function with
example.

ANSWER:-

We can define class members static using static keyword. When we declare a member of a class as static it means
no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is
created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside
the class as done in the following example by redeclaring the static variable, using the scope resolution
operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members −
ID NO-18CE082

#include <iostream>

using namespace std;

class Box {

public:

static int objectCount;

// Constructor definition

Box(double l = 2.0, double b = 2.0, double h = 2.0) {

cout <<"Constructor called." << endl;

length = l;

breadth = b;

height = h;

// Increase every time object is created

objectCount++;

double Volume() {

return length * breadth * height;

private:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box};

// Initialize static member of class Box

int Box::objectCount = 0;

int main(void) {

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects.

cout << "Total objects: " << Box::objectCount << endl;

return 0;}
ID NO-18CE082

When the above code is compiled and executed, it produces the following result −

Constructor called.
Constructor called.
Total objects: 2

Static Function Members:-


By declaring a function member as static, you make it independent of any particular object of the class. A static
member function can be called even if no objects of the class exist and the static functions are accessed using
only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other
functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You
could use a static member function to determine whether some objects of the class have been created or not.

Let us try the following example to understand the concept of static function members –

#include <iostream>

using namespace std;

class Box {

public:

static int objectCount;

// Constructor definition

Box(double l = 2.0, double b = 2.0, double h = 2.0) {

cout <<"Constructor called." << endl;

length = l;

breadth = b;

height = h;

// Increase every time object is created

objectCount++;

double Volume() {

return length * breadth * height;

static int getCount() {


ID NO-18CE082

return objectCount;

private:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

// Initialize static member of class Box

int Box::objectCount = 0;

int main(void) {

// Print total number of objects before creating object.

cout << "Inital Stage Count: " << Box::getCount() << endl;

Box Box1(3.3, 1.2, 1.5); // Declare box1

Box Box2(8.5, 6.0, 2.0); // Declare box2

// Print total number of objects after creating object.

cout << "Final Stage Count: " << Box::getCount() << endl;

return 0;

When the above code is compiled and executed, it produces the following result −

Inital Stage Count: 0


Constructor called.
Constructor called.
Final Stage Count: 2
ID NO-18CE082

OUESTION 12:-

What is the difference between C structure, C++ structure and class. How class can be specify?

ANSWER:-

OUESTION 13:-

Describe the concept of private member function of a class.

ANSWER:-

The private Members:-


A private member variable or function cannot be accessed, or even viewed from outside the class. Only
the class and friend functions can access private members.

By default all the members of a class would be private, for example in the following class width is a private
member, which means until you label a member, it will be assumed a private member −
ID NO-18CE082

class Box {
double width;

public:
double length;
void setWidth( double wid );
double getWidth( void );
};

Practically, we define data in private section and related functions in public section so that they can be
called from outside of the class as shown in the following program.

#include <iostream>

using namespace std;

class Box {

public:

double length;

void setWidth( double wid );

double getWidth( void );

private:

double width;

};

// Member functions definitions

double Box::getWidth(void) {

return width ;

void Box::setWidth( double wid ) {

width = wid;

// Main function for the program

int main() {

Box box;

// set box length without member function

box.length = 10.0; // OK: because length is public

cout << "Length of box : " << box.length <<endl;


ID NO-18CE082

// set box width without member function

// box.width = 10.0; // Error: because width is private

box.setWidth(10.0); // Use member function to set it.

cout << "Width of box : " << box.getWidth() <<endl;

return 0;

When the above code is compiled and executed, it produces the following result −
Length of box : 10
Width of box : 10

OUESTION 14:-

what is the purpose of copy constructor? Name two situations in which a copy constructors
executes

ANSWER:-

The copy constructor is a constructor which creates an object by initializing it with an object
of the same class, which has been created previously. The copy constructor is used to: Initialize
one object from another of the same type. Copy an object to pass it as an argument to a function.

When the compiler generates a temporary object. It is, however, not guaranteed that a copy
constructor will be called in all these cases, because the C++ Standard allows the compiler to
optimize the copy away in certain cases, one example is the return value optimization (sometimes
referred to as RVO).

When is copy constructor called?


In C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
ID NO-18CE082

OUESTION 15:-

What is virtual destructor? Discuss with small example. Can I overload any Destructor?

ANSWER:-

Virtual Destructor:-

Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in undefined
behavior. To correct this situation, the base class should be defined with a virtual destructor. For example,
following program results in undefined behavior.

// CPP program without virtual destructor


// causing undefined behavior
#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {
public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
ID NO-18CE082

getchar();
return 0;
}
Although the output of following program may be different on different compilers, when compiled using Dev-
CPP, it prints following:
Constructing base
Constructing derived
Destructing base
Making base class destructor virtual guarantees that the object of derived class is destructed properly, i.e., both
base class and derived class destructors are called. For example,

// A program with virtual destructor


#include<iostream>
using namespace std;
class base {
public:
base()
{ cout<<"Constructing base \n"; }
virtual ~base()
{ cout<<"Destructing base \n"; }
};
class derived: public base {
public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};
int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
ID NO-18CE082

getchar();
return 0;
}
Output:
Constructing base
Constructing derived
Destructing derived
Destructing base
As a guideline, any time you have a virtual function in a class, you should immediately add a virtual destructor
(even if it does nothing). This way, you ensure against any surprises later

OUESTION 16:-

What is dynamic initialization of objects? Why is it required? Illustrate with an example in C++.

ANSWER:-

Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an object is to
be provided during run time. Dynamic initialization can be achieved using constructors and passing parameters
values to the constructors. This type of initialization is required to initialize the class variables during run time.

Need of dynamic initialization


Dynamic initialization of objects is needed as

 It utilizes memory efficiently.

 Various initialization formats can be provided using overloaded constructors.

 It has the flexibility of using different formats of data at run time considering the situation.

Program example to explain the concept of dynamic initialization

#include <iostream>

using namespace std;

class simple_interest

float principle , time, rate ,interest;

public:

simple_interest (float a, float b, float c) {


ID NO-18CE082

principle = a;

time =b;

rate = c;

void display ( ) {

interest =(principle* rate* time)/100;

cout<<"interest ="<<interest ;

int main(){

float p,r,t;

cout<<"principle amount, time and rate"<<endl;

cout<<"2000 7.5 2"<<endl;

simple_interest s1(2000,7.5,2);//dynamic initialization

s1.display();

return 1;

Output
Enter principle amount ,rate and time
2000 7.5 2
Interest =300

COMPLEATE ASSIGNMENT PART ONE

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