Managing Memory in C++ - Dynamic Memory Allocation with Classes
Code:
Person.cpp
#include "Person.h"
#include <stdio.h>
#include <iostream>
Person::Person()
{
}
Person::Person(std::string fName, std::string lName)
{
firstName = fName;
lastName = lName;
}
Person::Person(std::string fName, std::string lName, int age)
{
firstName = fName;
lastName = lName;
ageData = age;
}
Person::~Person()
{
std::cout << "Person destructor called " << std::endl;
}
void Person::SetFirstName(std::string fName)
{
this ->firstName = fName;
}
std::string Person::GetFirstName()
{
return this ->firstName;
}
void Person::SetLastName(std::string lName)
{
this->lastName = lName;
}
std::string Person::GetLastName()
{
return this -> lastName;
}
void Person::SetAge(int age)
{
this ->ageData = age;
}
int Person::GetAge()
{
return this -> ageData;
}
void Person::SayHello()
{
std::cout << "Hello" << std::endl;
}
The main program
main.cpp
#include "Person.h"
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
Person *pOne = new Person("Tom", "Thumb", 25);
std::cout << "First name of pOne = "<< pOne->GetFirstName() << std::endl;
std::cout << "Memory address of pOne = " << &pOne << std::endl;
std::cout << "Last name of pOne = "<< pOne->GetLastName() << std::endl;
std::cout << "Age of pOne =" << pOne->GetAge() << std::endl;
pOne->SayHello();
delete pOne;
return 0;
}
The header file
Person.h
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED
#include <stdio.h>
#include <iostream>
class Person
{
private:
//string firstName;
std::string firstName;
std::string lastName;
int ageData;
public:
Person();
Person(std::string fName, std::string lName);
Person(std::string fName, std::string lName, int age);
~Person(); void SetFirstName(std::string fName);
std::string GetFirstName();
void SetLastName(std::string lName);
std::string GetLastName();
void SetAge(int age);
int GetAge();
void SayHello();};
#endif // PERSON_H_INCLUDED
Last updated