Showing posts with label class and object. Show all posts
Showing posts with label class and object. Show all posts

April 08, 2025

Constructor and Destructor

 Constructor and Destructor

● A class constructor is a special member function of a class that is executed whenever we

create new objects of that class.

● A constructor will have exact same name as the class and it does not have any return type

at all, not even void.

● Constructors can be very useful for setting initial values for certain member variables.

There are three types of constructor in c++. They are:

1. Default Constructor.

2. Parametrized Constructor.

3. Copy Constructor.

Default constructor

Default constructor is the constructor which doesn't take any argument. It has no parameter.

Syntax:

class_name ()

{

//constructor definition

}

Example:

int main(){

Cube c;

cout<<c.side;

}class Cube

{

public:

int side;

Cube()

{

side=10;

}

};

Output: 10




Parameterized constructor

These are the constructors with parameter. Using this Constructor you can provide different

values to data members of different objects, by passing the appropriate values as argument.

Syntax:

Class_name (arg1,arg2,…)

{

//constructor code

}

Example:

#include<iostream.h>

#include<conio.h>

class Cube{

public:

int side;

Cube(int x)

{

side=x;

}

};

int main()

{

Cube c1(10);

Cube c2(20);

Cube c3(30);

cout<<c1.side;

cout<<c2.side;

cout<<c3.side;

}

Output:

10

20

30



Copy Constructor

These are special type of Constructors which takes an object as argument, and is used to copy

values of data members of one object into other object.

Syntax:

class_name (class_name &ref)

{

//code

}

Example:

#include<iostream.h>

#include<conio.h>

class A{

int a,b;

public:

A(int x, int y)

{

a=x;

b=y;

}

A(A &ref) //copy constructor

{

a=ref.a;

b=ref.b;

}

void show()

{

Cout<<a<<” ”<<b<<endl;

}

};

void main()

{

A obj1(10,20);

A obj2=obj1;

obj1.show();

obj2.show();

getch();

}



Destructor

● Destructor is used to destroy the object that have been created by a constructor .

● Destructor can never take any argument and it does not return any value.

● Invoked implicitly by the program to cleanup the storage.

Syntax:

~ destructor_name()

{

}

Example:

#include<iostream.h>

#include<conio.h>

int count=0;

class alpha{

public:

alpha(){

count++;

cout<<”no of object created”<<count;

}

~alpaha(){

cout<<”no of object destroyed”<<count;

count--;

}

};

void main()

{

alpha A1,A2,A3;

}


April 04, 2025

C++ Old Question Solution

What makes the OOP better than POP? Explain with features of OOP.

Solution:

POP stands for 'Procedural Oriented Programming' which is the conventional programming approach. In POP, the entire program is viewed as a sequence of things to be done such as taking input, calculating and printing and the entire program is divided into smaller programs known as function and it gives more emphasis to function.

Object-oriented programming is the most recent concept in computer programming paradigms and it has been defined as "an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand".

Being the recent programming approach, OOP offers several benefits than POP approach and some of the most important benefits are as follows:

  • In OOP, through inheritance, we can eliminate redundant code and extend the use of existing classes.
  • Due to the uses of class, encapsulation is possible so that the necessary data members and the necessary member function for these data members can be wrapped inside the single unit called 'class' 
  • By using the proper access specifier like 'private' or 'protected', data can be hidden so that only the required member function can access them.
  • In OOP, polymorphism is possible so that we can use the same operator or function to perform the various types of operations. For example, the operator can be used to find the sum of any two numeric values as well as to combine two string, Like 10+30 or "wel"+"come".
  • We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity.
  • The principle of data ding helps the programmer to build secure programs that cannot be invaded by code in offer parts of the program.
  • It is easy to partition the work in a project based on objects.
  • Objected oriented system can be easily upgraded from small to large system.
  • Message passing technique for communication between objects makes the interface description with external systems much simpler.
  • Software complexity can be easily managed.

The constructors can't declared as virtual but the destructors can be declared as virtual. Why?

solution:

The virtual keyword is used in C++ when we need dynamic behavior. It will work only when objects exists where constructors are used to create objects. Constructors will be call at the time of object creation.So if we define the constructor as virtual,it should have existing object to use. But the object is created at the time of constructor call. Thus this is contradictory.
Again we can't override the constructor,when any method is declared as virtual,it should be overridden in its derived class. Since constructor is used for initializing variables of a class and it can be defined only within the class ,it can't be overridden. Thus the constructor can't be declared as virtual. We can use virtual destructor because, at the time of calling destructor,we have the objects .So we can use virtual keyword for the destructors.


What sorts of shortcomings of structure are addressed by classes? Explain giving appropriate example.
Solution:

 We know that structure is a collection of heterogeneous data elements under a common name. It is a convenient tool for handling a group of logically related data items. It is a user-defined data type with a template that serves to define its data properties. Although structure is a user-defined data type, but it has some limitations.

    Class is a collection of data members and member function bundled together as a unit. Using class, encapsulation as well as data hiding has been possible. Similarly, inheritance and polymorphism has been possible due to class. So, it is the more advanced data structure than the structure of C and it has been removed the drawbacks of the structure. The main drawbacks of structure of Care as follows:

  • The standard C does not allow the struct data type to be treated like built-in data types. For example
            struct complex

            {

                float real;

                float imaginary;

            };

        struct c1,c2,c3;

        c3=c1+c2;

               The member variable of structure 'complex' can easily be assigned values using                       the dot(.) operator, but we cannot add two complex numbers or subtract one from                     the other. So, c3=c1+c2 or c3=c1-c2 both are illegal in C.

            But, in C++, we can design a complex class and add or subtract them using + or-                   operator by the help of polymorphism. For example:

          class complex

        {

            private:

                    float real;

                    float imaginary;

            public:

                    complex operator+(operator);

                    complex(float, float);

          }

        Complex c1.c2,c3;

        C3=c1+c2;

  • Another important limitation of C structure is that they do not permit data hiding. Structure members can be directly accessed by the structure variables by any function anywhere in their scope. So, structure members are public members.

           For example:

            The data members of the structure can be easily accessed by the structure variable                  in any part of the program such as c1.real, c1.imaginary even from the 'main()'                         function but the data members of the class cannot be accessed directly outside their                 member function. So, c1.real or c1.imaginary is not allowed directly in the 'main()'                     function of the program.

  • Another limitation of structure is that the member of one structure cannot be transferred to the another structure but 'class' of COP has solved this limitation so that the features of one class can be easily transferred to another class by means of inheritance.


What is message passing ? Describe with example.
Solution:



























class rectangle 

{

    public:

        void area(int l, int b)

        {

            cout<<"area="<< a;

        }

};

void main()

{

    rectangle r1;

    r1.area(10,5); //example of message passing

}



The constructors can't declared as virtual but the destructors can be declared as virtual.why?

solution:
The virtual keyword is used in C++ when we need dynamic behavior. It will work only when objects exists where constructors are used to create objects. Constructors will be call at the time of object creation.So if we define the constructor as virtual,it should have existing object to use. But the object is created at the time of constructor call. Thus this is contradictory.
Again we can't override the constructor,when any method is declared as virtual,it should be overridden in its derived class. Since constructor is used for initializing variables of a class and it can be defined only within the class ,it can't be overridden. Thus the constructor can't be declared as virtual. We can use virtual destructor because, at the time of calling destructor,we have the objects .So we can use virtual keyword for the destructors.






















Class and Objcet

 

class and object:

class:

  • 1.       a class is a way to bind data and associated function together.
  • 2.       it allows data and function to hidden if necessary for external use.
  • 3.       defining a class means creating a user defined data type that behaves as built in data.
  • 4.       once a class has been declared we can create any number of object belonging to that class.

syntax:

class class_name

{

private:

data member;

member function;

public:

data member;

member function;

};          //end of class

 

Generally data are placed in private section and function are placed in public section.

  • 5.       class contains both data and function . Data are called data member and function are called member function.
  • 6.       data and function are defined in private section are not accessible out of the class.
  • 7.       data and function placed in public section are only accessible from outside the class.
  • 8.       the word private is optional . the data in function of class by default private.


Object:

An object is an instance of a class.

For example, the Car class defines the model, brand, and mileage. Now, based on the definition, we can create objects like

Car suv;
Car sedan;
Car van;

Here, suvsedan, and van are objects of the Car class. Hence, the basic syntax for creating objects is:

Class_Name object_name;

Example 1: Class and Objects in C++

#include <iostream>
using namespace std;

class Car {
  public:

    // class data
    string brand, model;
    int mileage = 0;

    // class function to drive the car
    void drive(int distance) {
        mileage += distance;
    }
    
    // class function to print variables
    void show_data() {
        cout << "Brand: " << brand << endl;
        cout << "Model: " << model << endl;
        cout << "Distance driven: " << mileage << " miles" << endl;
    }
};

int main() {
    
    // create an object of Car class
    Car my_car;

    // initialize variables of my_car
    my_car.brand = "Honda";
    my_car.model = "Accord";
    my_car.drive(50);

    // display object variables
    my_car.show_data();

    return 0; 
}


Recent Posts

Oracle 19c Installation guide (Linux/ Windows)

Most Viewed Posts