C++: Implementing a method

This entry is part 28 of 61 in the series C++

In our earlier examples, there is only data members in our class.  Using our previous example, notice that in the main, we have a few cout statements to print out the strings.

Say we are working on a program where we need to retrieve data and display similar statements.  Developing a method in our class will make a lot of sense.

In this example, we work out a method called Display for the class.

#include <iostream>
#include <string>

using namespace std;

class Rock

	string name;
	string track;

	int Display();

	Rock(string, string);  //This is the constructor
	~Rock();  //This is the destructor


int Rock::Display()

	cout << "This is " << name << " Singing " << track;
	cout << endl;

	return 0;

Rock::Rock(string name2, string track2)
	name = name2;
	track = track2;

	cout << "This is Rod Stewart Signing Off";
	cout << endl;

int main()

	string name1 = "Rod Stewart";
	string track1 = "I was only Joking";

	Rock rockstar(name1,track1); // instance declaration


	return 0;

Once the method is created, we will first have to declare an instance for the class Rock.  In our case, we use rockstar as the name of the instance.

In line, we have the actual method implementation.  The method needs to be scoped under the class Rock since the method belongs to this class.

To access the method, we  need to use the dot(.) operator as shown below.



Series Navigation<< C++: Methods of a class
C++: Reusing a method >>

Leave a comment

Leave a Reply