Home » C++ programs » C++ Class and Objects 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

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.

Example:

#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





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.