1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn about C++ Classes and Objects

By David Bolton, About.com

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;
public:
Book( int Numpages) ; // Constructor
~Book(){} ; // Destructor
void SetPage( int PageNumber) ;
int GetCurrentPage( void ) ;
};

Book::Book( int NumPages) {
PageCount = NumPages;
}

void Book::SetPage( int PageNumber) {
CurrentPage=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.

1 of 9

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Introduction to C++ Classes and Objects

©2008 About.com, a part of The New York Times Company.

All rights reserved.