Basic Concept of Memory Management in a C++ Class | CodeGuru

Basic Concept of Memory Management in a C++ Class

Have you ever paid attention to memory management when using classes? I have an elementary quiz about the basic concept of memory management in standard C++. This quiz is from my teaching experience because I found many programmers usually make the same mistake. Now, take a look at the quiz. Please don’t worry if you […]

Written By
CodeGuru Staff
CodeGuru Staff
Apr 8, 2008
1 minute read
CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More

Have you ever paid attention to memory management when using classes? I have an elementary quiz about the basic concept of memory management in standard C++. This quiz is from my teaching experience because I found many programmers usually make the same mistake.

Now, take a look at the quiz. Please don’t worry if you cannot give a answer. Paying attention to such code from now on is the most important thing you need to learn.

Quiz

How does the following code work?

What will happen during the running process? Why?

If there is a problem, how will you solve it?

class A
{
private:
   char* pchTest;
public:
   explicit A(char* const pchInitialText);
   virtual ~A();
   char* GetContent(void)const{return pchTest;}
};

A::A(char* const pchInitialText)
{
   pchTest = new char[strlen(pchInitialText)+1];
   strcpy(pchTest,pchInitialText);
}

A::~A()
{
   delete [] pchTest;
   pchTest = NULL;
}

void show(A clsAtest)
{
   printf("%s",clsAtest.GetContent());
}

int main(void)
{
   A Atest("Just Test!");
   show(Atest);
   return 0;
}

Hints

How is the parameter transferred into the functions as shown below?

void FunctionName(ValueType  para);
void FunctionName(ValueType *para);
void FunctionName(ValueType &para);

Have any idea? I will share my thoughts on the next page.

CodeGuru Logo

CodeGuru covers topics related to Microsoft-related software development, mobile development, database management, and web application programming. In addition to tutorials and how-tos that teach programmers how to code in Microsoft-related languages and frameworks like C# and .Net, we also publish articles on software development tools, the latest in developer news, and advice for project managers. Cloud services such as Microsoft Azure and database options including SQL Server and MSSQL are also frequently covered.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.