Q:

C++ | Assign values to the private data members without using constructor

belongs to collection: C++ programs on various topics

0

C++ | Assign values to the private data members without using constructor

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In the below program, we are creating a C++ program to assign values to the private data members without using constructor.

/* C++ program to assign values to the 
private data members without using constructor */

#include <iostream>
#include <string>
using namespace std;

// class definition
// "student" is a class
class Student {

private: // private access specifier
    int rollNo;
    string stdName;
    float perc;

public: //public access specifier
    //function to set the values
    void setValue()
    {
        rollNo = 0;
        stdName = "None";
        perc = 0.0f;
    }

    //function to print the values
    void printValue()
    {
        cout << "Student's Roll No.: " << rollNo << "\n";
        cout << "Student's Name: " << stdName << "\n";
        cout << "Student's Percentage: " << perc << "\n";
    }
};

int main()
{
    // object creation
    Student std;

    //calling function
    std.setValue();
    std.printValue();

    return 0;
}

Output

Student's Roll No.: 0
Student's Name: None
Student's Percentage: 0
 

See the above code, we created a method named setValue() – In the method definition, we are assigning default values to the private data members.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ | Create an empty class (a class without data ... >>
<< C++ | Define a class method outside the class defi...