×

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

Create a class with public data members only in C++

Here, we are going to learn how to create a class with publish data members only in C++?
Submitted by IncludeHelp, on October 14, 2018 [Last updated : March 01, 2023]

C++ class with public data members only

Let's understand

  1. What is data member?
    Any variable declared inside the class in known as 'data member' of the class.
  2. What is public data member?
    A variable declared inside the 'public' section of the class is known as 'public data member'.

In this example, we are going to create a class with the pubic data members, a public data member can be accessed outside of the class with object name, and public data member's value can be set and get outside of the class with its object name.

So, here in this example,

  • Number is the class name.
  • num is an integer data member, which is declared in the public section of the class - so it is a public data member.
  • In the main, N is the object to class Number.
  • N.num is using to set and then get the value.

C++ program to create a class with public data members only

#include <iostream>
using namespace std;

//class declaration
class Number {
public:
    int num;
};

//Main function
int main()
{
    //creating object
    Number N;

    //setting value to public data member
    N.num = 100;

    //printing value
    cout << "value of N.num = " << N.num << endl;

    return 0;
}

Output

value of N.num = 100

Related Programs

Comments and Discussions!

Load comments ↻





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