In this section, we will cover introduction to objects, classes, constructors and difference between structures and classes in C++.

An Introduction to Objects and Classes

Two things are important in this regard:

  • Intrinsic data types:
  • User defined data types:

Intrinsic data types are those which are already present with the compiler for example:

  • int
  • char
  • float

Whereas, User Data Types/Abstract Data Types (ADTs) are those which are defined by the user using structure and classes. The reason that these data types are termed as abstract is: the user gets enough flexibility to use it according to his needs, whereas, in intrinsic data types is restricted to its limited use, e.g: an int is used to store and integer value, one cannot get an out put of type float by using the data type int.

What is an object?

An object can be defined as the elements through which we perceive the world around us. These elements have recognizable attributes and particular behavior. An object also exhibit state which means: We can describe what an object is, and what it does.

More precisely: an object can be defined as:

Object =  data (usually private)+ processes (usually public)

What is a Class?

This is user defined data type. It is composed of two things:

  • The data members
  • The member functions

The private part of the class contains any elements which are to be hidden from public access. The public part of the class defines the behavior (method) of any object of the class. Behavior means a process which the object is able to perform. This is the general practice to put attributes into the private part of the class and behavior in the public part of the class, but this is not mandatory.

Example: 1

// classes example
#include <iostream>
using namespace std;
class CRectangle
{
    int width, height;
  public:
    void set_values (int,int);
    int area ()
	{
	return (width * height);
	}
};
void CRectangle::set_values (int a, int b)
{
  width = a;
  height = b;
}

int main ()
{
  CRectangle rect;
  rect.set_values (3,4);
  cout << "rect area: " << rect.area();
  CRectangle rectb;
  rectb.set_values (5,6);
  cout << "rectb area: " << rectb.area();

  getchar();
  return 0;
}
Output:
rect area: 12
rectb area: 30

Notice that the call to rect.area() does not give the same result as the call to rectb.area(). This is because each object of class CRectangle has its own variables x and y, as they, in some way, have also their own function members set_value() and area() that each uses its object’s own variables to operate.

Please Note

  • ‘class’ is the key word
  • The name following ‘class’ keyword is the name of the class.
  • Private area holds the data members (usually)
  • Public area holds the member functions (usually)
  • The data members are not initialized in the private area of the class
  • Objects has recognizable identities (attributes) and behavior
  • Object contains the data and the methods
  • Object provides link between data and the methods. This is what which is called encapsulation or information hiding.
  • By information hiding we mean: protecting program from accidental alteration of data. And obviously this factor is achieved from private part of the class.
  • There can be more than one instances of a class
  • Members functions are always accessed through the instance of the class with the help of  a dot operator.
  • The member functions (defined outside the class) are always defined with the help of a scope resolution operator , which is denoted by two colons e.g (::)

Constructors

Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. For example, what would happen if in the previous example we called the member function area() before having called function set_values()? Probably we would have gotten an undetermined result since the members x and y would have never been assigned a value.

In order to avoid that, a class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type; not even void.

Example: 2

We are going to implement CRectangle including a constructor:

// example: class constructor
#include <iostream>
using namespace std;
class CRectangle {
    int width, height;
  public:
    CRectangle (int,int); // replaced set_values() with constructor
    int area () {return (width*height);}
};
CRectangle::CRectangle (int a, int b) {
  width = a;
  height = b;
}

int main () {
  CRectangle rect (3,4);
  CRectangle rectb (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}

Output:

rect area: 12
rectb area: 30

As you can see, the result of this example is identical to the previous one. But now we have removed the member function set_values(), and have included instead a constructor that performs a similar action: it initializes the values of x and y with the parameters that are passed to it.

Structures and Classes

Structures can be used in almost exactly the same way that you use classes. The only formal difference between class and struct is that in a class the members are private by default, while in a structure they are public by default. Let us make it understand with the help of an example.

Example: 3

class foo
{
private:
	int data1;
public:
	void func();
};

Because private is the default in classes, this keyword is unnecessary. You can just as write

class foo
{
     	int data1;
public:
	void func();
};

and the data1 will still be private. Many programmers prefer this style. But including private keyword increases clear readability.

If you want to use a structure to accomplish the same thing as this class, you can dispense with the keyword public, provided you put the public members before the private ones:

struct foo
{
void func();
private:
	int data1;
};

since public is the default. However, in most situations programmers don’t use a struct this way. They use structures to group only data, and classes to group both data and functions.

 Acknowledgement:

Most of the contents above have been taken directly from here solely for the purpose of education.

Exercises

  1. Using classes write a C++ program that can calculate the area of a circle. The formula  for finding the area is: π r2
  1. Create a Class that will calculate and print out bills for the city water company. The class has three data members: account (type int), code (type char), and water_used (type float). You need to provide set and get methods for each of these data members. In addition, provide a member function named calculateAmount that prints amount due for the user. Amount should be calculated on the basis of following formula: The water rates vary, depending on whether the bill is for home use, commercial use, or industrial use. A code of h means home use, a code of c means commercial use, and a code of i means industrial use. Any other code should be treated as an error. The water rates are computed as follows:
Code h: 5.00 PKR plus 0.0005 per gallon used
Code c: 1000 for the first 4 thousand gallons used and 0.00025 for each additional gallon
Code i: 1000 if the usage does not exceeds 4 thousand gallons;2000 of the usage is more than 4 thousand but does not exceed 10 thousand gallons;3000 of usage exceeds 10 thousand gallons

Write a main function to test this class.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.