Define a class Student having the following private attributes with parameterized constructor - allpakhub

 OBJECT-ORIENTED PROGRAMMING (C++)

 

We are learning about the following things by this example:

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

 


Task Example:

QUESTION:

 

Define a class Student having the following private attributes

· name (char *)

· age int

· CGPA (double)

 Now do the following operations on above-mentioned class:

 · Write parameterized constructor ().

 

Solution

#include <iostream>

#include <string>

using namespace std;

class Student

{

private:

            string name;

            int age;

            double CGPA;

public:

            Student()

            {

                        name = '\0';

                        age = 0;

                        CGPA = 0.0;

            }

            Student(string n, int a, double result)

            {

                        name = n;

                        age = a;

                        CGPA = result;

            }

            void Setname(string n)

            {

                        name = n;

            }

            void Setage(int a)

            {

                        age = a;

            }

            void SetCGPA(double result)

            {

                        CGPA = result;

            }

            string Getname(string n)

            {

                        name = n;

            }

            int Getage(int a)

            {

                        age = a;

            }

            double GetCGPA(double result)

            {

                        CGPA = result;

            }

            void display()

            {

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

                        cout << endl << endl << endl;

                        cout << "Name of Student is: " << name << endl;

                        cout << "Age of Student is:  " << age << endl;

                        cout << "CGPA of Student is: " << CGPA << endl << endl;

            }

};

int main()

{

            Student obj;

            string a;

            int b;

            double c;

            cout << "Please enter Name: ";

            cin >> a;

            cout << "Please enter Age:  ";

            cin >> b;

            cout << "Please enter CGPA:  ";

            cin >> c;

            obj.Setname(a);

            obj.Setage(b);

            obj.SetCGPA(c);

            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