Classes and objects in C++

Dmitrii Korolkov

Let’s talk about classes and objects in c++ in a simple way. Consider class as just the user-defined data type. Class has it’s own variables (data types) and method (functions) that could be accesses by instance of this class – object. Let’s take a look at the syntax:

class Pandoraxx {

 // access specifier – either private, public or protected

public:

// data members  int Number or string MyString, etc.

string Hello;

//Defining the function inside of the class

void HelloFunction() {

std::cout << Hello << std::endl;

};

}

int main() {

Pandoraxx object1; // declaring the object of the class

object1.Hello = “Hello World”;

// accessing the function using object

object1.HelloFucntion();

return 0;

}

The following code demonstrates the example of creating the class and object. Easy and straight forward, right? Speaking about functions, there are 2 ways to define the function: inside of class definition or outside. What’s the difference? The code above has the function HelloFunction() that is defined inside of the class. Let’s have a look at another way, outside of class:

class Hello {

int Sentence;

void SayHello(); // SayHello is not defined inside of  the class Hello

};

int main {

void Hello::SayHello() {

std::cout << “Hello World” << std::endl;

}

}

To define a function outside of the class we are using scope resolution operator ::, in Hello::Sayhello() , where as you noticed, Hello is a class name, Sayhello() is the function that was declared in the class Hello. Now, we come up with the question, why we need to declare the function outside of the class? Well, the big advantage is that defining a function in the class makes it sometimes too complicated and non-readable.

There  is a good task to solve from one of the good courses from Udemy that you can find here: click me. The problem to solve:  

/* Create and implement a class called Time. Have a method on the class called Init that takes in the hour, minute and second in 24 hour time.

This class should be able to:

– Display the time in 12 hour format

– eg. 12:10:01 am – 12 hours, 10 minutes and 1 second in the morning

– Display the time in 24 hour format

– eg. 22:10:05 – this is 10:10:05 pm in 12 hour time

You should not have to change the internal data representation of the class to display in either format */

If you stuck, you can try my solution which you can access from codeshare.

proudly runned on WordPress