1. Technology

Learn about C++ Classes and Objects


1 of 9

Starting with C++ classes
Objects are the biggest difference between C++ and C. One of the earliest names for C++ was C with Classes.

Classes and Objects

A class is a definition of an object. It's a type just like int. A class resembles a struct with just one difference : all struct members are public by default. All classes members are private.

Remember : A class is a type, and an object of this class is just a variable.

Before we can use an object, it must be created. The simplest definition of a class is

 class name {
 // members
This example class below models a simple book. Using OOP lets you abstract the problem and think about it and not just arbitrary variables.
 // example one
 #include <iostream>
 #include <stdio.h>
 class Book
 int PageCount;
 int CurrentPage; 
 Book( int Numpages) ; // Constructor
 ~Book(){} ; // Destructor
 void SetPage( int PageNumber) ;
 int GetCurrentPage( void ) ;
 Book::Book( int NumPages) {
 PageCount = NumPages;
 void Book::SetPage( int PageNumber) {
 int Book::GetCurrentPage( void ) {
 return CurrentPage;
 int main() {
 Book ABook(128) ;
 ABook.SetPage( 56 ) ;
 std::cout << "Current Page " << ABook.GetCurrentPage() << std::endl;
 return 0;
All the code from class book down to the int Book::GetCurrentPage(void) { function is part of the class. The main() function is there to make this a runnable application.

On the next page : Understanding the example.

©2014 About.com. All rights reserved.