×

C++ Programs

C++ Most popular & Searched Programs

C++ Basic I/O Programs

C++ Constructor & Destructor Programs

C++ Manipulators Programs

C++ Inheritance Programs

C++ Operator Overloading Programs

C++ File Handling Programs

C++ Bit Manipulation Programs

C++ Classes & Object 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 [Last updated : March 01, 2023]

Assigning values to the private data members without using constructor

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

/* 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.

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.