UPI Study › Courses › C++ Programming › Free lessons › Lesson 9.3 Free with a free account
Classes With Member Functions
C++ Programming · Chapter 9: Structs, Classes, and File StreamsSection 9.3 · lesson 61 of 84video coming soon
← Making Structs SmarterNext lesson: Initialization Inside Classes →
In this lesson
Embedding behavior within data structures.
- Declare a class with data members and member functions
- State what public and private permit
- Define member functions inside and outside the class
- Use this; split a class across header and source
Transcript
Everything said in the video, section by section (1,364 words). Read along, or search it.
Lesson Overview
Data and Functions Declared Together
So far, data has been one thing, and the functions that act on it another. A class puts them in the same declaration. The values a thing holds, and the operations it'll perform on request, written together and named as one type. This lesson covers the notation: how to declare one, where to define its functions, what public and private do, and how to split it across two files.
Core Idea
Classes, Objects, and the Parking Bay
The design idea was sketched much earlier: a unit that holds its own data, together with the operations permitted on it, asked to act rather than reached into. A class is how C++ writes that down. It declares a new type. Each variable of that type is an object, holding its own values. The functions declared inside are member functions, callable on any of those objects. A parking bay, for example, has a private half: its data, a number and whether it's occupied, reachable only from inside the class. And a public half: what it'll do, occupy, vacate, and is free, callable from anywhere. The dividing line isn't a style choice. The compiler enforces it.
Declaration Syntax
Anatomy of the Bay Class
Here's the shape. Class Bay. Everything after private, until the next label, is reachable only from within the class: the data members, number and occupied. Everything after public is callable from outside: assign, occupy, vacate, and is free. The labels apply downward until another appears, and either may be used more than once. And the whole declaration ends with a semicolon after the closing brace. Omitting it is the single most common error here. Notice that these members have no starting values yet. A freshly created bay holds whatever was already there. That's why assign exists. Giving members values automatically is the next topic.
Access Rules
What Public and Private Allow
Here's what the two labels do, from different vantage points. Inside a member function of the class, touching a private member is legal. In main, on an object, it's not. Writing b dot occupied equals true fails to build. Here is the real message. The same holds in any unrelated function. Public members, though, are reachable from everywhere. And the last case surprises people. Inside another bay's member function, reaching other dot occupied is legal. Access is granted per type, not per object. A member function of Bay may reach the private members of any Bay it can see.
Default Access
Class Versus Struct Defaults
Members written before any label are private in a class, and public in a struct. That's the only difference between the two keywords. Everything in this lesson works identically with either. Because the default is easy to forget, write the label explicitly, even when it matches the default. A reader should never have to remember which keyword you used to know what's reachable.
Defining Outside
Qualifying Definitions With the Class Name
Short functions can stay in the class body. Longer ones are usually declared inside and defined outside, which keeps the declaration readable as a summary of what the type offers. Inside, assign and is free are just declarations, ending with semicolons. Outside, the definition says which class it belongs to: void Bay colon colon assign. Read it as the assign that belongs to Bay. And inside the body, members are named directly, with no prefix. Leave the Bay prefix off, and you've declared an ordinary free function that happens to share a name. It then fails at the first mention of number, because a free function has no members to speak of. The Bay prefix is what ties the definition to the class.
Design Choice
Deciding Where Functions Are Defined
So where should a member function be defined? Inside the body, when it's one or two lines, such as returning a value or setting a flag. The declaration stays short enough to read at a glance. Outside, with the Bay prefix, for anything longer, and for everything once the class is split across files. The declaration then reads as a list of what the type offers. The Bay prefix uses the same operator you met when reaching a global name, now with a name in front of it. It says which scope the name after it belongs to.
Worked Example
Three Bays With Separate Data
Objects are created like any other variable. Here, first, second and third are three bays. First dot assign 1, second dot assign 2, and third dot assign 3. The dot names the object the call acts on. First dot occupy changes first only. So first is free prints 0, and second is free prints 1. Each object carries its own data members. But the member functions are written once, and act on whichever object they were called on. Three sets of values, one set of operations, which is why every call has to name an object.
The this Pointer
Reaching Members Through this
Inside a member function, a bare member name means the member of the object this call was made on. That object is also available explicitly, under the name this, and its members are reached with an arrow. Most of the time you never write it. The members are found without help, as occupied is here. It becomes necessary when a parameter has the same name as a member. Here, the parameter number shadows the member number, so this arrow number reaches the member, on the left, and the parameter is on the right. Run it: it prints 7, so the member really was set. That's the shadowing rule you met earlier, applied to a new pair of scopes. Naming the parameter differently avoids it entirely, and many people prefer that.
Two Files
Splitting Into Header and Source
Once a class is more than a few lines, it moves out of the program file into a pair of its own. The header, Bay dot h, holds the declaration: the data members and the function headings, wrapped in an include guard. The source file, Bay dot cpp, includes its own header first, and holds the bodies, each with the Bay prefix. Every file that wants to use the type includes the header. The definitions are compiled once. Built together, the program prints 0.
File Contents
What Belongs in Each File
Here's what belongs where. The class declaration goes in the header, because every file using the type needs to know its shape. So do the data member declarations, private or not, and the member function headings. Member function bodies go in the source file, where they're compiled once. Put them loose in a header, and including it twice causes duplicate definitions. And the include guard goes in the header, so the declaration isn't read twice in one build. The three-line if-not-defined pattern is portable. A single line, pragma once, does the same job, and every compiler you're likely to meet supports it. What matters is that every header has one.
Common Mistakes
Recognizing Typical Error Messages
Here are faults worth recognizing on sight. Expected semicolon after class means the semicolon after the closing brace is missing. Use of undeclared identifier number, in what should be a member function, means it was defined without the Bay prefix. Is a private member of Bay means code outside the class touched a private member. And if an assignment inside a member function seems to do nothing, a parameter is usually shadowing the member. Undefined symbols, naming Bay assign, means a member function was declared, but never defined. Here is the linker message. The compiler accepts the call. Only the linker, looking for the body, notices it's missing. And redefinition of Bay means a header included twice with no guard. Here is that message too. An include guard in Bay2.h is the fix.
Quick Check
Predicting the Box Copy Output
Quick check, with a new class. Box keeps its value private, and its copy function reads o dot v, the private value of another Box. Does this compile? And if it does, what does it print? Pause and predict. It compiles. O dot v is private, but access is granted per type, and o is a Box. It prints 9, then 1. A copied b's value while it was 9, and b's later change to 1 touched only b.
Key Takeaways
Summary of Class Essentials
To summarize. A class holds private data and public operations, and the compiler enforces the line between them. Write public and private explicitly. Outside the class, qualify member function definitions with the class name. Each object has its own data, while the member functions are written once. And put the declaration in a header, and the bodies in a source file.
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Classes With Member Functions
What do public and private mean in a C++ class?
How do I define a C++ member function outside the class?
When do I need to use the this pointer in a C++ member function?
How do I split a C++ class into a header file and a source file?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →