Constructors in oop (object oriented programming) c++

 Constructors

Task 1

Consider the definition of the following class:
class Sample{
private:
int x;
double y;
public:
Sample( ); //Constructor 1
Sample(int); //Constructor 2
Sample(int , int); //Constructor 3
Sample(int, double); //Constructor 4
};
(a) Write the definition of constructor 1 so that the private data members are initialized to 0.
(b) Write the definition of constructor 2 so that the private data member x is initialized
according to the value of the parameter, and the private data member y is initialized to 0.
(c) Write the definition of constructor 3 and 4 so that the private data members are initialized
to according to the values of parameters.

#include<iostream>

using namespace std;

class Sample{

private:

       int x;

       double y;

public:

       Sample()

       {

              x = 0; y = 0;

              cout << "Value in 1st constructor is:" << x << ":" << y << endl;

       }

       Sample(int a)

       {

              x = a;

              y = 0;

              cout << "Value in 2nd constructor is:" << x<<":"<<y << endl;

       }

       Sample(int a, int b)

       {

              x = a; y = b;

              cout << "Value of 3rd constructor is:" << x << ":" << y << endl;

       }

       Sample(int a, double b)

       {

              x = a; y = b;

              cout << "Value in 4th constructor is:" << x << ":" << y << endl;

       }

};

int main()

{

       int a=1,z=5;

       double b=10.1;

       Sample();

       Sample(10);

       Sample(a, z);

       Sample(a, b);

       getchar();

       getchar();

       return 0;

}

 

 

 

 

 

Task 2:

Write a program that defines a class Area, with data members PI=3.1419 and radius r. and
radius is input by user. The program should use data members and the functions listed to
accomplish the following.
(a) PI is initialized through Constructor
(b) Prompt the user to input the value of a double variable r, which stores the radius of a
sphere.
The program then outputs the following Surface area of the sphere. 4*PI*R

 

 

#include<iostream>

using namespace std;

class Area{

       int pi;

       int radius;

public:

       Area()

       {

              pi = 3.14;

              radius = 0;

       }

       void out(int r);

};

int main()

{

       int r;

       cout << "Enter the

radius:";

       cin >> r;

       Area();

       Area yo;

       yo.out(r);

       getchar();

       getchar();

       return 0;

}

void Area::out(int r)

{

       radius = r;

       int full;

       full=4 * pi*radius;

       cout << "Area of the

sphere is:" << full << endl;

}

Comments

Popular posts from this blog

Multiple inheritance,friend function and multiple file in oop(object oriented programming)

Concepts of OOP (object oriented programming)

Concepts in c++........