Home » C++ programs

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

Here, we are going to learn how to assign values to the private data members without using constructor in C++ programming language?
Submitted by IncludeHelp, on February 21, 2020

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.