C++ – Classes and Objects, Part I

What I’m learning from Lesson 9 in Sam’s Teach Yourself C++ in One Hour a Day, 8th Edition

Object-oriented programming (OOP) is a different way of thinking about programs. Typically, beginner programmers are introduced to procedural programming — code is organized into different functions. The code can usually be read from the top to bottom, and the flow can be recognized.

With OOP, as the name suggests, you are encouraged to think of your data as different objects. For example, think of a human. A human is an object that has attributes, such as first name, last name, height, weight, etc. This human object can also carry out methods, or do things, such as speak, jump, eat, sleep, etc.

With this way of thinking about programming, you can then organize your code into different objects, each describing a specific part of your program and executing the logic piece by piece.

Declaring a Class

The way to encapsulate your data into an object with attributes and methods is by using the class construct. Here’s a basic example:

class Human {
  string firstName;
  string lastName;
  short int height;
  short int weight;

  void Speak(string quote);
  void Jump(int howHight);
  void Eat(string food);
  void Sleep(int duration);
}

Objects

An object is a specific instance of a class. This allows you to actually use a class.

Two ways to create an object:

Human firstMan; // Similar to defining any other type
Human * firstMan = new Human(); // Dynamically created. Will need to use delete to deallocate

Accessing Attributes and Methods

You can use the dot operator:

firstMan.Speak("Hi.");
Human * secondMan = new Human();
(*secondMan).Speak("Hello!"); // If using a pointer then you must dereference first in order to use dot operator.

You can also use the pointer operator (when using pointers to an object):

secondMan->Speak("Test test");

Public and Private Keyword

In a class you are allowed to declare attributes and methods as either publicly available or privately.

Public means they can be accessed (possibly modified) outside of the class (i.e. they can be “seen” by the rest of the program.). Private means that they can only be accessed from within the class. This is useful, because there may be data that you don’t want the user to have access to directly. So, you “hide” it in the private area of the class. As it can be accessed from within the class, you can create a public method that will indirectly access the private data. This gives you control on what specific data a user can access and how they can access it. This is known as abstraction.

class Human {
private:
int age;
int dob;
public:
int height;
int weight;
int GetAge() { return age; } // Returns value of private variable

}

In Part II, I’ll go over constructors.

Advertisements