# 8.2 — Classes and class members

While C++ provides a number of basic data types (eg. char, int, long, float, double, etc…) that are often sufficient for solving relatively simple problems, it can be difficult to solve complex problems using just these types. One of C++’s more useful features is the ability to define your own data types that better correspond to the problem being worked upon. You have already seen how enumerated types and structs can be used to create your own custom data types.

Here is an example of a struct used to hold a date:

Enumerated types and data-only structs (structs that only contain variables) represent the traditional non-object-oriented programming world, as they can only hold data. If you want to initialize or manipulate this data, you either have to do so directly, or write functions that take a DateStruct as a parameter:

In the world of object-oriented programming, we often want our types to not only hold data, but provide functions that work with the data as well. In C++, this is typically done via the class keyword. Using the class keyword defines a new user-defined type called a class.

Classes

In C++, classes are very much like structs, except that classes provide much more power and flexibility. In fact, the following struct and class are effectively identical:

Note that the only difference is the public: keyword in the class. We will discuss its function in the next lesson.

Just like a struct definition, a class definition does not declare any memory. It only defines what the class looks like.

 Warning: Just like with structs, one of the easiest mistakes to make in C++ is to forget the semicolon at the end of a class declaration. This will cause a compiler error on the next line of code. Modern compilers like Visual Studio 2010 will give you an indication that you may have forgotten a semicolon, but older or less sophisticated compilers may not, which can make the actual error hard to find.

In order to use a class, a variable of that class type must be declared:

In C++, when we declare a variable of a class, we call it instantiating the class. The variable itself is called an instance of the class. A variable of a class type is also called an object.

Member Functions

In addition to holding data, classes can also contain functions! Here is our Date class with a function to set the date:

Just like member variables of a struct or class, member functions of a class are accessed using the member selector operator (.):

Note that in the original struct version of SetDate(), we needed to pass the struct itself to the SetDate() function as the first parameter. Otherwise, SetDate() wouldn’t know what DateStruct we wanted to work on.

However, in our class version of SetDate(), we do not need to pass cToday to SetDate()! Because SetDate() is being called on cToday, the member variables in SetDate() will refer to the member variables of cToday! Thus, inside function SetDate(), m_nDay is actually referring to cToday.m_nDay. If we called cTomorrow.SetDate(), m_nDay inside of SetDate() would refer to cTomorrow.m_nDay.

Using the “m_” prefix for member variables helps distinguish member variables from function parameters or local variables inside member functions. This is useful for several reasons. First, when we see an assignment to a variable with the “m_” prefix, we know that we are changing the state of the class. Second, unlike function parameters or local variables, which are declared within the function, member variables are declared in the class definition. Consequently, if we want to know how a variable with the “m_” prefix is declared, we know that we should look in the class definition instead of within the function.

By convention, class names should begin with an upper case letter.

Here’s another example of a class:

This produces the output:

Name: Alex  Id: 1  Wage: $25 Name: Joe Id: 2 Wage:$22.25


Warning: One of the most common C++ mistakes is to forget to end all class (and struct) declarations with a semicolon. This can cause the compiler to report all sorts of weird, seemingly-unrelated errors!

 8.3 -- Public vs private access specifiers Index 8.1 -- Welcome to object-oriented programming
1. cAlex.Print();
cJoe.Print();

return 0;
}; ======> LINE 41

Semicolon in line 41 after }

Infact i copy pasted whole code and compiled it and didnt get any error with “}; ” even with semicolon after closing braces.Does compiler ignore that?

Thanks,
Renu

• It’s possible to declare stuff after the end of main() -- for example, other variables, functions, etc… The compiler treats that ; as a blank statement, which compiles to nothing. So it’s essentially ignored. There’s no reason for that ; to be there (it was a typo), but it doesn’t hurt either. (As a note to future readers, I removed the extraneous semicolon).

• semicolon is required at the end of the #class }; not in the end of the #main function.

2. I get build errors the on beginning example when trying to initialize manually.

The error is: “expected constructor, destructor, or type conversion before ‘.’ token.

Also, not quite sure why the & reference for the &sDate in the SetDate function?
Is this so just passing the reference instead of whole structure when calling the
function?

p.s. Love these lessons

• Hmm, that’s an odd one. Is the code that uses sToday inside a function, or is it floating in global space? Declarations can be in global space, but code that executes instructions can not be. I would put the following code:

inside your main() function and then see if it works. I suspect it will.

Also, as far as the & goes, that means we’re passing a DateStruct by reference instead of by value. This will allow SetDate to modify the actual sDate we pass in instead of just a copy.

3. This is the whole thing I’m trying…

If I comment out setting the global sToday members and use the ones in main()
it works O.K. but not vice versa. So…. you can assign a value to global variables
when they are declared but not members of a struct? (int myInt = 5;)
Unless I’m making a syntax mistake somewhere. Need grouping braces? {} ?

• I see what you are trying to do. Yeah, you can’t assign struct variables in global space that way. If you want to initialize your global struct, you have to do it like this:

• The author doesn’t seem to understand pointers correctly.
The usual way to write this code is:

And then called it like this:

The thinking is this.
You want something changed. Therefor you need to give the function the address of what needs to be changed. So the input argument must be a pointer. (Hence the *sSDate). When you call the function, you pass it the address of what needs to be changed.

4. i have a very fundamental problem.
a ‘class’ is declared. it has one ‘private data-member’ and one ‘public member-function’.

an object (instance of the class) is created after the ‘closing curly brackets and the semicolon’ of the class-declaration.

what is the address of the class ?
what is the address of the class-object ?
what is the address of the member-function ?

please enlighten me to keep up my tempo of persuing c++.

thanks
prabhakar.

• The class itself does not have an address, because it is just a definition.

An object of the class does have an address, because it is an actual variable. You can find the address by using the address-of (&) operator:

Member functions also have an address, because you can set a pointer to them, and you can pass their address into a function:

ptr is a pointer to a member function of Foo that takes no parameters and returns an integer. It is being set to the address of the Foo::GetValue() function.

5. hi alex..

still i am confusing about using strncpy..

following line in ur program how its work i still didnt understand

strncpy(m_strName, strName, 25);

kind regards

• strncpy simply copies N character of a zero-terminated string into another string. So the above line copies 25 characters from strName to m_strName.

• Alex,

But don’t we have to de-reference the strName pointer to copy the value? I noticed that even if we dereference the pointer like below, it gives positive results.

Does strncpy() takes care of extracting a string from an address?? or is it something else?

Regards,
Mayur.

6. Hi Alex, Great site!

My question is, why can’t I take the address of a member function through an instance? For example:

class foo
{
void fooFun(){};
};

main()
{
foo x;
void (*MyfooFun)() = &x.fooFun;
}

• Actually, you can, but you have to get the syntax right, and the syntax is so horrid I always have to look it up every time I want to use it.

• Thanks, Alex, however that syntax does not compile (for me at least). The error message explicitly suggests using

&Foo::Fun

and not

pfcnX.Fun

if I use

&pfcnX.Fun

the error is:

‘&’ : illegal operation on bound member function expression

Anyway, you’ve shown me how to do it via the class scope syntax and I agree with you that the
usage is pretty ugly!
(PS I used the tags but they don’t work for me)

• and

both seem to work under Visual Studio 6. Microsoft’s compilers are sometimes permissive in that they will allow you to do things that aren’t officially part of the C++ spec -- I’m not sure if this is one of them.

Also, I think I fixed the issue with the PRE tags (finally), for future reference.

7. hello everybody

I copid the following code and compiled it. It gives the error “Explicit decleration of function ‘int strcpy()’ ”

• Hi

Which compiler r u using?. I have no problems. I use Code::Blocks studio, the open source cross platform IDE.

• To Alex:

Thanks for this excellent tutorial.

I also have some problems with this code. I am using Code::Blocks 8.02. I use GCC compiler.

When I compile it, I have the following error:
…HElloWorld/main.cpp|13|error: ‘strncpy’ was not declared in this scope|

I then add “#include “. Everything works fine except I still get the warning:

…/HElloWorld/main.cpp|31|warning: deprecated conversion from string constant to ‘char*’|

to compile with g++ and it will compile. Note that you will still get the warnings, but they are just warnings, not errors; you can ignore the warnings and you will get valid output.

• When you’ll run the class Employee through g++ you’ll get some warnings:

1) You must include the string library because it will not recognise you the strncpy
‘strncpy’ was not declared in this scope

2) You have to put const in front of your char pointer otherwise you’ll receive an warning like below:
deprecated conversion from string constant to ‘char*’

So to solve this warning you have to make like that:

void SetInfo(const char *strName, int nID, double dWage)
{

}

8. Superb tutorial!

In the Employee class, I would rather have the statement

using namespace std;

after the #include rather than in the middle of Employee.Print().

9. Hello,

I am a beginner in C++….I have a few doubts/questions regarding the classes programs above..

In the above program of Today’s date, it prints the Today’s date, either you declare it directly in (), like (7,31,2009) or you enter it manually using ‘cin’ for each of the month, date and year.
But if I want the program to print the Tomorrow’s and Yesterday’s date by default, after getting the Today’s date as input, how could I go for it (using ‘class’ offcourse)?

- Prem

• simply you will make a function let’s name it tomorrowdate and you will add 1 to day and the same to months and years but of course you have to but if conditions to mange this system as there are some months that consists of 30 and others of 31 and another if condition to add 1 to months if day > 31 or 30 you must choose depending on the month no. and so on, i hope i helped u 😀

10. This section needs rewrite because, apparently, struct is grossly underestimated here and the following code works like a charm:

11. Hi Alex,
Why the size of empty Class is one byte?
Why the size of empty structure is 0 byte?

Regards,
Srinu.

• Here’s some insight to that:

http://bytes.com/topic/c/insights/660463-sizeof-empty-class-structure-1-a

Basically, if it were size 0 and you made an array out of it, since each array element is 0 in size the entire array would occupy 0 and there would be no way to differentiate say position 0 from position 3

12. Hi Alex,
I m not getting the meaning of this line

“Just like a struct definition, a class definition does not declare any memory.”

13. Hi Alex, just so you know in this code

is supposed to be

Quick question, why do you use DateStruct &sDate in the function instead of just DateStruct sDate (with no ampersand)

14. Hi, I have a question.. Can one class be used to initialize another class? Something like this:

When I tried to do this, I had some problems in passing parameters to ‘class One’ from ‘class Two’.

Thanks

• HI ellanKavi

Yes u can go ahead and make object of one class in other class ..This is called COMPOSITION ,because the new class is composed of existing class.

just look the example below to get more info on how to pass parameter

class One
{
private :
int m_temp ;
public :
One(){m_temp = 0;} // this is the default Constructor

void set(int i) // This the setter of the class
{
m_temp = i ;
}
};

class Two
{

public :
One NewOne ; // Embedded Object

};

int main ()
{
Two objTwo ;
objTwo.NewOne.set(37); // access the embedded object
return 0 ;
}

You can also go ahead and make a parameterised constructor in the class One and then the value can be passed as a parameter when the class One is instanciated .

Regards
Biraj Borah
Pune

Question 2:
Consider the above figure. You can determine the position of a point using the point’s coordinate. Using a class, you need to write a complete C++ program to determine which part a point belongs to based on these :
i. the black area shows that the point is in 1st quadrant
ii. the blue area shows that the point is in 2nd quadrant
iii. the red area shows that the point is in 3rd quadrant and
iv. the green area shows that the point is in 4th quadrant.
If the point is in any part of the y axis, (see the y point), then point is said to be at the x axis. And if the point is at any part of the x axis (see the x point), then it is said to be y axis.
Your program should also provide a constructor function to enables an object to be initializes when it is declared.

16. Hi can you explain me the difference between the class declaration and definition , I am bit confused about this .

class example
{
int a ;
public :
fun () { ….}
};

is this is called as a class declaration or definition ?

17. Wondering if using a class to replace struct is a good idea? And if Mahesh is right, the only different would then be that a class can go private (among other things)!

18. Mahesh IS right.

Alex wrote “In C++, classes are very much like structs, except that classes provide much more power and flexibility”.

But to nitpick, I think he meant to say “In C++, classes and structs are very much like structures in C, except that they provide much more power and flexibility”.

In fact, C++ classes and structs are identical - in the sense that a struct can be/do anything that a class can be/do, and vice versa.

Here is the exhaustive list of differences between a class and a struct:

1. By default, class members are private, struct members are public.
2. By default, classes are inherited privately, structs are inherited publicly.

19. Hi,
I can not understand what is the advantage of “class” relative to “struct”.
It seems they both do the same thing.
Whether advantage of the class is reduction of defined functions out of the main() ?

20. Hi Alex,
Not sure if you still respond to the queries here,
I’d a query, as I understand, there are no significant differences b/w struct and classes except access specifiers. then Why did we have separate datatype class? we could have use struct in C++.

21. Dear Alex,
I just copied your code into my codeblocks compiler. But it is showing the following errors.
C:\Users\ANIS\Desktop\C++ practice\text.cpp||In member function ‘void Employee::SetInfo(char*, int, double)’:|
C:\Users\ANIS\Desktop\C++ practice\text.cpp|12|error: ‘strncpy’ was not declared in this scope|
C:\Users\ANIS\Desktop\C++ practice\text.cpp||In function ‘int main()’:|
C:\Users\ANIS\Desktop\C++ practice\text.cpp|30|warning: deprecated conversion from string constant to ‘char*’|
C:\Users\ANIS\Desktop\C++ practice\text.cpp|33|warning: deprecated conversion from string constant to ‘char*’|
||=== Build finished: 1 errors, 2 warnings ===|

22. @anismizi,
I hope you figured out the issue with the sample code if not, or possibly to help others confused one thing was left out of the code snip. At the top of the file using ‘strncpy’ you need to include “string.h”. It should show: #include

23. #include
class Employee
{
public:
char m_strName[25];
int m_nID;
double m_dWage;

// Set the employee information
void SetInfo(char *strName, int nID, double dWage)
{
strncpy(m_strName, strName, 25);
m_nID = nID;
m_dWage = dWage;
}

// Print employee information to the screen
void Print()
{
using namespace std;
cout << "Name: " << m_strName << " Id: " <<
m_nID << " Wage: $" << m_dWage << endl; } }; int main() { // Declare two employees Employee cAlex; cAlex.SetInfo("Alex", 1, 25.00); Employee cJoe; cJoe.SetInfo("Joe", 2, 22.25); // Print out the employee information cAlex.Print(); cJoe.Print(); return 0; } this is the last example of this chapter. can u tell me why have we used a pointer *strname as a parameter in setinfo function.what if we do not use a pointer? 24. CAN I HEARD SOMEONE SAID WEBSITE PROGRAMMING CANT HELP…… THAT MEANS YOU ARE CONFIRMED “ODE”.. I HAVE LEARNT ALOT VIA WEBSITE PROGRAMMING….. UNLESS YOU DONT NO WAT U AR READING…MAYBE YOUR MIND-SET IS SOME WHERE ELSE… 25. void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year) { sDate.nMonth = nMonth; sDate.nDay = nDay; sDate.nYear = nYear; } DateStruct sToday; // Init our date to the same date using the function SetDate(sToday, 10, 14, 2020); Mr Author I Have a problem in the first argument of the function definition…..you declared a struct variable using ‘&’ sign…….but i couldn’t understand it why you used it……….i tried in my IDE without using & sign but it displayed error: “saying Warning 1 warning C4700: uninitialized local variable ‘sToday’ used” ……….what does this mean…….and you passed sToday structure into the function…..does that mean the name sToday is an address itself…..Please help me with this…… 26. The following program was made mostly by copypasting the authers code and flags 3 compiler errors: /home/isaac/c++/tests/main.cpp|16|error: ‘cToday’ does not name a type| /home/isaac/c++/tests/main.cpp|17|error: ‘cToday’ does not name a type| /home/isaac/c++/tests/main.cpp|18|error: ‘cToday’ does not name a type| ||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===| #include class Date { public: int m_nMonth; int m_nDay; int m_nYear; }; Date cToday; // declare a variable of class Date // Assign values to our members using the member selector operator (.) cToday.m_nMonth = 10; cToday.m_nDay = 14; cToday.m_nYear = 2020; using namespace std; int main() { int x = cToday.m_nDay; cout << x << endl; return 0; } 27. Develop a payroll application to compute the salary for the employees in an organization. Class Employee has general information namely employee_id, employee name, department_name, address, mobile number and email?id. There are two types of employees such as training professionals and regular employees. The Definition of Pay_calculate() will be different for different types of employees. Include suitable menu for navigating the application. Training professionals has total teaching experience, qualification, no_of_sessions_handled. Salary = no_of_sessions_handled*one_day_salary (Both can be randomized values) Regular employees has department they belong to, basic_pay, designation Gross Pay = basic_pay+HRA+DA Net Pay = Gross Pay – PF HRA = 9% of Basic Pay, DA = 90% of Basic Pay, PF = 20% of Basic Pay SNo Designation Basic_Pay 1 Manager 30000 2 Technical Lead 25000 3 Senior Software Engineer 20000 4 Software Engineer 15000 • Get and display details of different types of employees using operator overloading(<>) • Write suitable exceptions for the given scenario . • Write a friend function LiseDeptWise() to list all employees for a given department_name. 28. Hi Alex, Nice page! best for the beginner. However, its bit misleading as structures can also have member functions in cpp. Please add that information else people understand member functions cannot be there in structure as the major difference between c/c++. Cheers, Deepesh 29. #include <iostream> class Employee { public: char m_strName[25]; int m_nID; double m_dWage; // Set the employee information void SetInfo(char *strName, int nID, double dWage) { strncpy(m_strName, strName, 25); m_nID = nID; m_dWage = dWage; } // Print employee information to the screen void Print() { using namespace std; cout << "Name: " << m_strName << " Id: " << m_nID << " Wage:$" << m_dWage << endl;
}
};

int main()
{
// Declare two employees
Employee cAlex;
cAlex.SetInfo("Alex", 1, 25.00);

Employee cJoe;
cJoe.SetInfo("Joe", 2, 22.25);

// Print out the employee information
cAlex.Print();
cJoe.Print();

return 0;
}
I decided to compile this text but I have some errors

testtest.cpp: In member function ‘void Employee::SetInfo(char*, int, double)’:
testtest.cpp:12:39: error: ‘strncpy’ was not declared in this scope
strncpy(m_strName, strName, 25);
^
testtest.cpp: In function ‘int main()’:
testtest.cpp:30:35: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
cAlex.SetInfo("Alex", 1, 25.00);
^
testtest.cpp:33:33: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
cJoe.SetInfo("Joe", 2, 22.25);
^

30. I’ve been taught to instantiate classes in other OOP languages like so:

Does C++ not require you to do this? What happens if you do it this way?

31. if you use Visual studio 2012
use

or you will get  unsafe error

i like this website i read alot books on c++ and this is best i have seen

32. There’s a small typo in here:

It should’ve been int nYear.

33. This article needs a lot of improvement. structs offer the same functionality as classes, the only difference is members of structs are public by default and classes are private. That is the only difference. Stroustrup came up with classes instead of making structs private is because of the issue of backward compatibility. This article is misleading, for example

can be defined as
void SetDate( int nMonth, int nDay, int Year)
{
sDate.nMonth = nMonth;
sDate.nDay = nDay;
sDate.nYear = nYear;
}
even for a structure and this function can be called using a struct object just like a class . Eg.

This code compiles and works exactly like a class.

• This was a really good comment.  Thanks for sharing this interesting information.

34. I had an ERROR in code::blocks:
error: ‘strncpy’ was not declared in this scope
--------
and one more question:
is it important that classes be out of main()?

35. Hi All,

I get the code running as it should, but I get a warning (inside xcode) when I call

xcode warns me that

ISO C++11 does not allow conversion from string literal to ‘char *’

I can get rid of it by first defining a char[] in which I hold the string and then passing that to the class, like so

is that good form?

again, it runs fine, I’m just wondering what exactly it means and if it could point to a possible compatibility problem?

Is there an alternative way that would avoid this warning?

Thanks for the great site!

best,

wim

36. Hi:
When using classes and structs to define an object, is it normal to have all your switch/case statements in your main() such as when a user is presented with a menu and the properties they enter are used to create the object name and its properties from the class or struct?
Or should a function handle this and if so how?
Thanks,
Willy

37. Please correct the line no. 10 of 2nd code example from void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year) to void SetDate(DateStruct &sDate, int nMonth, int nDay, int nYear)

38. Alex…we can also have a member function inside structs too!!…and we can manipulate them just lyk classes do…infact the example u shown to draw the difference b/w "struct" & "class"..in that DateStruct we can define it’s own member function and from it we can initialize those "struct" fields…It’s not necessary to define a new function and then pass the entire “struct” inside it..Correct me if m wrong???

The only difference b/w "class" and "struct" is that all the members of a "struct" are  "public" by default…while classes provide us "access-specifiers" to enhance data-hiding…this is the importance of classes over structured programming..

39. when talking about class and struct definitions(probably others exist) and how they do not take "dynamic" memory i think it wold be good if you also say that they will take "static" memory due the size of the executable that is being compiled. there are (modern ;)) devices being made with insufficient storage space and someone might get surprised by that.(even if the surprised one is some end-user, not the programer)

40. You forgot to #include cstring in the last example. strncpy is used without including that header.

Alex, you didn’t use any semicolon after member functions and the code compiles fine. But if I put a semicolon there, compiler doesn’t give any error. Does the semicolon(after member function) makes difference at some cases or it Is always optional?

• Thanks for the note about cstring.

The semicolon isn’t needed to terminate member functions (just like normal functions don’t end in a semicolon). If you use them in that capacity, the compiler will just ignore them.

41. Not sure if i should report this but i guess it can be confusing for newbies so here is a typo :

void SetDate(DateStruct &sDate, int nMonth, int nDay, int Year)

The last parameter should be nYear instead of Year.

• Fixed. Thanks for noticing!

42. I’m having problem with the last example, my compile keep reporting the error: "deprecated conversion from string constant to ‘char’". Please help me out!!!! Not sure its my compiler or the code….

• Can you tell me what line is causing the error? It’s unclear from your note where the error is.

• They are line 32 and 35!!!!

• Ah! I see what it’s complaining about. Passing a string literal to a char* parameter in SetInfo() is dangerous.

I’ve updated the prototype of SetInfo as follows:

Note the addition of const before char *strName. That should resolve the issue.

• It works !!! Ty Alex

43. Hi Alex,

In the class Employee example code, is there a reason why you’re not using std::string at line 12? Isn’t that the more modern way to work with strings? (i think you said this yourself in an earlier post).

• When I wrote this lesson originally, I hadn’t introduced std::string yet by this point.

As I’ve been rewriting the tutorials, I moved the introduction to std::string earlier because it’s so useful.

I haven’t gotten around to rewriting this lesson yet. When I do, I’ll migrate the examples from C-strings to std::string.

44. Hi Alex, looking at your code above. In the setDate() method  why do we declare the variables as ‘ m_nID = nID , m_dwage = dwage’ etc… When we are not going to use them anywhere? because if you look at your print() method,for example - m_nID is called instead of nID.

• First, it’s important to understand that each class object contains an instance of its member variables. So cAlex has it’s own m_strName, m_nID, and m_dWage.

Now, we want to initialize these values. We could write:

But instead, we’ve written a function to do that for us:

nId and dWage are standard function parameters whose values are passed in by the caller. nId and dWage get destroyed at the end of the SetInfo() function so they can’t be used outside of this function. This function simply assigns values to the member variables from the parameters.

The last question is: How does SetInfo know whose member variables to set? That’s up to the caller as well. In this case:

Make sense?

45. (II) 1. Develop a payroll application to compute the salary for the employees in an organization. Class
Employee has general information namely employee_id, employee name, department_name, address,
mobile number and email‐id. There are two types of employees such as training professionals and regular
employees. The Definition of Pay_calculate() will be different for different types of employees. Include
suitable menu for navigating the application.
Training professionals has total teaching experience, qualification, no_of_sessions_handled.
Salary = no_of_sessions_handled*one_day_salary (Both can be randomized values)
Regular employees has department they belong to, basic_pay, designation
Gross Pay = basic_pay+HRA+DA Net Pay = Gross Pay – PF
HRA = 9% of Basic Pay, DA = 90% of Basic Pay, PF = 20% of Basic Pay
SNo Designation Basic_Pay
1 Manager 30000