You are here:About>Computing & Technology>C / C++ / C#> C++> Learn C++ Programming> Introduction to C++ Classes and Objects
About.comC / C++ / C#
Newsletters & RSSEmail to a friendSubmit to Digg

Learn about C++ Classes and Objects

From David Bolton,
Your Guide to C / C++ / C#.
FREE Newsletter. Sign Up Now!

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. Starting with C++ classes
  2. Understanding the Book Class
  3. More about the Book Class
  4. Learn about Writing Class Methods
  5. Learn about Inheritance and Polymorphism
  6. Learn about Inheritance
  7. What is Polymorphism?
  8. Learn about C++ Constructors
  9. Tidying Up - C++ Destructors

Previous | Next >>

 All Topics | Email Article | | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.