Answer to Question #15932 in C++ for sjaiva

2012-10-05T07:20:50-0400

Question #15932

expalaine with examples the classes and objects on C++

Expert's answer

2012-10-09T09:11:42-0400

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.

In the main() function a variable ABook of type Book is created with the value 128. As soon as execution reaches this point, the object ABook is constructed. On the next line the method ABook.SetPage() is called and the value 56 assigned to the object variable ABook.CurrentPage. Then cout outputs this value by calling the Abook.GetCurrentPage() method.When execution reaches the return 0; the ABook object is no longer needed by the application. The compiler generates a call to the destructor.

Declaring Classes

Everything between Class Book and the } is the class declaration. This class has two private members, both of type int. These are private because the default access to class members is private.The public: directive tells the compiler that access from here on is public. Without this, it would still be private and prevent the three lines in the main() function from accessing Abook members. Try commenting the public: line out and recompiling to see the ensuing compile errors.

This line below declares a Constructor. This is the function called when the object is first created.

& Book( int Numpages) ; // Constructor It is called from the line& Book ABook(128); This creates an object called ABook of type Book and calls the Book() function with the parameter 128.