Define a class Cat having attributes with constructors - allpakhub

 OBJECT-ORIENTED PROGRAMMING (C++)

 

We are learning about the following things by this example:

  • Classes in C++
  • Constructors
  • Parameterized Constructors
  • Generic Data Input

 

Define a class Cat having attributes with constructors - allpakhub

Task Example:

QUESTION:

 

Define a class Cat having attributes

1. name (char *)

2. weight (double )

Now do the following operations on above mentioned class:

·         Write default constructor, parameterized constructor.

·         Write a display() function to display attributes of class Cat on screen.

Solution

 

#include <iostream>

#include <string>

using namespace std;

class Cat

{

public:

            string name;

            double weight;

            Cat()

            {

                        name = '\0';

                        weight = 0.0;

            }

            Cat(string n, double w)

            {

                        name = n;

                        weight = w;

            }

            void Setname(string n)

            {

                        name = n;

            }

            void Setweight(double w)

            {

                        weight = w;

            }

            string Getname()

            {

                        return name;

            }

            double Getweight()

            {

                        return weight;

            }

            void display()

            {

                        cout << "\n\n\t --RESULT--\n";

                        cout << "  Name of Cat:  " << name << endl;

                        cout << "  Weight of Cat:  " << weight << endl<<endl;

            }

};

int main()

{

            Cat obj;

            string a;

            double b;

            cout << "Enter Name of Cat: ";

            cin >> a;

            cout << "Enter weight of Cat: ";

            cin >> b;

            obj.Setname(a);

            obj.Setweight(b);

            obj.display();

            system("pause");

            return 0;

}

That's exactly what today's post is all about. We hope you'll like it. You can also message us to see more posts, and if you like it, be sure to share it with your friends. Thank you very much for reading.

 

-----------------------------------------------------------------------------------

Post a Comment

0 Comments