Hello World C++ with Objects

Ok… this is a “Hello World” program in C++ using objects. It illustrates a number of aspects of object oriented programming in C++ allowing you to get a quickstart into C++ programming. First there is the #include directives which tells C++ that the program uses two libraries, iostream and string (actually they specify the header files that define the libraries to be used). “iostream” provides input/output to streams, in this case we are sending a stream to the console. “string” is a string type library that provide a string datatype that is not native to the base C++, this allows us to manipulate strings in an easy manner.

#include <iostream.h>
#include <string.h>
using namespace std;

class oHello
{
    string hstr;
public:
    oHello();
    ~oHello();
    void print();
};

oHello::oHello()
{
    hstr = "Hello World\n";
}

oHello::~oHello()
{
}

void oHello::print()
{
    cout << hstr;
}

>int main()
{
    oHello myObject;
    myObject.print();
    return 0;
}

Class oHello is defined as having three methods, oHello method is the constructor that is executed when the object is created, ~oHello is the destructor that is executed when the program destroys the object (in this case, when the program terminates), lastly there is print which sends hstr to the output stream. These are declared as public so that they can be accessed from other modules in the program that are not members of the oHello object class. “hstr” is private to the class and only the class methods can access this data. It is of type string, the object string that was defined in the string class library.

The oHello method does one thing, assign hstr the value of “Hello World\n”. “\n” means add a carriage return to the end of the string. Now, when any member methods access hstr it would contain the value “Hello World\n”.

The print method contains the instruction cout << hstr, this calls the hstr object using the << method which directs it to send the value it contains to the cout stream class, which as stated earlier sends the data to the output stream.

Now that all the objects are defined… we can use them in the main() function which is automatically executed when the program is run. First we create an instance of the oHello object, called myObject. Next we call the print method of the myObject object, which prints “Hello World\n” to the output stream (in this case the console). Lastly since main() is a function it must return something before terminating, so we return the value zero.