News

C++ Tutorials



 Classes with Objects (OOP) "Sciencefactsblog.blogspot.com"
Classes are at the heart of nearly every object-oriented programming language. They allow us to structure our code in ways that represent the real-life domain that our program applies to. Additionally, classes allow us to better design programs by splitting up data and behavior into logical units that interact with one another using strict sets of predefined rules.
What is a class?

Simply put, a class is a custom data type. More specifically, a class is a custom data type that contains within it it's own data (member data) and functionality (member functions, or methods).

Classes are used for things that need to be represented by data types far more intricate than primitive types such as integers, characters, and boolean values. For example, we might want to write a program for a library that keeps track of what books are available, what books have been checked out, and who currently has which books.

To do this, we could represent each book as a simple string representing the title. But this has many limitations. For example, each book is far more than just a title; books have many other pieces of information associated with them, such as the author, publication date, ISBN, page count, and so on.

To more accurately represent a book, we'd like to create our own Book[i] data type, which could then contain all of the information about that book in a single unit. Once we have our [i]Book data type, we can then use that type throughout the rest of our program. Can you see how this would make our program less convoluted and easier to manage?
Writing your first C++ class

Let's dive right in with a simple C++ class that will demonstrate the basics.

In C++, most classes will use two files to contain their code:

The header file, usually ending with .h, will contain our class declaration. The class declaration tells the compiler what the class is, what kind of data it will hold, and what kind of things it will be able to do.

The body file, usually ending with .cpp, will contain our definitions. The class definitions tell the compiler how to do the things that it is able to do.

For the rest of this tutorial, we will be looking at a simple class, Dog. Let's start by creating the header file for our class.

Open up a text editor and create a new file. Save this file as "Dog.h". Write the following in your Dog.h file:
CPP Code: [ Select ] [ Line Numbers Off ]
1.    class Dog {
2.     
3.    };


Congratulations! You've just declared your first class in C++. Note the syntax for declaring a class: we use the class keyword, followed by the name of the class we wish to create, followed by opening and closing curly braces, and finally a semicolon.

If we want to use this class in our program, we simply declare variables of this type. Instances of classes are called objects. For example, the following line creates an integer named "num" and a new Dog object named "woofy":
CPP Code: [ Select ] [ Line Numbers Off ]
1.    int num;    // declare an integer
2.    Dog woofy;  // declare a Dog


Right now our class is empty, that is, it contains no data or behavior. At this point, our class is rather useless, but we're going to change that.
Member Data

Member data refers to data (variables) contained within your class. These variables are said to be members of the class. Any type of data can be a member of a class: integers, characters, doubles, and so on.

There are three levels of access that can be assigned to members of a class: public, protected, and private.



Object oriented Programing Fetures
public:
Members that are declared public can be accessed by any methods of the class and by anything outside of the class.

protected:
Members that are declared protected can be accessed by any methods of the class and by any methods belonging to subclasses of the class. (Subclasses are outside the scope of this tutorial, so we will not be seeing any protected data members for now.


private:
Members that are declared private can only be accessed by methods of the class. They are inaccessible to any other parts of the program.

Let's jump right in and add a data member to our Dog class. What kind of information about a Dog can we add? Let's start with a simple one: it's age. All dogs have an age, so our dog class should include data to represent this. Let's add an integer to hold how old the dog is, in years:
CPP Code: [ Select ] [ Line Numbers Off ]
1.    class Dog {
2.     
3.    public:
4.       int age;
5.     
6.    };


In the code above, we have added an integer variable, age, as an integer in our Dog class. Note the syntax for declaring data members: the scope of the variable (in the case, public), a semicolon, followed by the variable declaration.

Now that our Dog class has a public data member, we can access this variable through out Dog objects using the dot (.) operator.
CPP Code: [ Select ] [ Line Numbers Off ]
1.    Dog woofy;   // declare a Dog called woofy
2.    woofy.age = 5;  // set woofy's age to 5

Member Functions (Methods)

You should be familiar with functions, so defining methods is pretty easy. A method is a function that belongs to a class, much in the same way that a data member is a variable that belongs to a class. While member data describes what a class is, methods describe what a particular class can do.

Just like with member data, the same three levels of access can be assigned to methods of a class: public, protected, and private.

public:
Methods that are declared public can be invoked by any other part of the class and by anything outside of the class.

protected:
Methods that are declared protected can be invoked by any other method of the class and by any method of subclasses of the class. (Again, subclasses are outside the scope of this tutorial, so we will not be seeing any protected methods for now.)

private:
Methods that are declared private can only be invoked by other methods of the class. They are inaccessible to any other parts of the program.

Alright, think of an action that a Dog would typically perform. How about barking? Dogs love to bark, and our Dog will be no different. Let's go ahead and add a method, bark, to our Dog class:
CPP Code: [ Select ] [ Line Numbers Off ]
1.    class Dog {
2.     
3.    public:
4.       int age;
5.       void bark();
6.     
7.    };


Note the syntax for declaring methods: it is remarkably similar to declaring data members. The syntax should look familiar to you, since we are essentially declaring a function, the only difference here is that this function is a member of our class. Also note that we do not need to say public again -- any member or method declarations made under the public scope identifier will be declared as public until we specify otherwise.

Now that we've declared our method, we need to actually define it so that it does something useful. This is where our .cpp file comes into play.

Create a new text file and save it as "Dog.cpp". Be sure to save it in the same directory as your Dog.h file that we've been working with. In Dog.cpp, write the following lines:
CPP Code: [ Select ] [ Line Numbers Off ]
1.    #include "Dog.h"
2.    #include <iostream>
3.     
4.    void Dog::bark() {
5.     
6.       std::cout << "Woof!" << std::endl;
7.    }


Let's go through this file line by line. On line 1, we include our Dog.h header file so that we can define the methods for our Dog class. We include the iostream header on line 2 to allow for standard output.

Now note the syntax for defining our method:

return-type class-name::method-name()

Defining a method of a class is very similar to defining a plain old ordinary function. The major difference is that we prefix the method name with the name of the class to which it belongs.

Now we can call our bark() method like this:
CPP Code: [ Select ] [ Line Numbers Off ]
1.    Dog woofy;   // declare a Dog called woofy
2.    woofy.bark();  // tell woofy to bark

Conclusion

You now have a basic understanding of how to create and use classes in C++. There are far more advanced things we can do with classes, but we'll save those for the next tutorials.


_______________________________________________

0 comments:

Post a Comment