Classes in C++

C++ can be used for object-oriented programming. This example shows you how to define a class and a header file belonging to it.

The header file for the Person class

// Person.h

#pragma once

#include <string>

using namespace std;

class Person
{
public:
	Person(void);
	Person(string name, int age);
	~Person(void);
	string name;
	int age;
};

The Person class

// Person.cpp

#include "StdAfx.h"
#include "Person.h"

Person::Person(void)
{
}

Person::Person(string name, int age){
	this->name = name;
	this->age = age;
}

Person::~Person(void)
{
}

The main program

// Main.cpp

#include "stdafx.h"
#include "Person.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	// Create an instance of Person
	Person* person = new Person("Santa",191);

	// Print the name and age to the console
	cout << "Name: " << person->name << "\n";
	cout << "Age: " << person->age << "\n";

	system("pause");

	return 0;
}

Output:

Name: Santa
Age: 191
Press any key to continue . . .
This entry was posted in C++ and tagged , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?