-
August 9th, 2012, 10:25 AM
#1
[RESOLVED] Class help using constructors and destructors.
bake.cpp
Code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Walnut
{
public:
int Size;
};
class Squirrel
{
private:
Walnut *MyDinner;
public:
Squirrel();
~Squirrel();
};
Squirrel::Squirrel()
{
cout << "Starting!" << endl;
MyDinner = new Walnut;
MyDinner->Size = 30;
}
Squirrel::Squirrel()
{
cout << "Cleaning up my mess!" << endl;
delete MyDinner;
}
int main()
{
Squirrel *Sam = new Squirrel;
Squirrel *Sally = new Squirrel;
delete Sam;
delete Sally;
system("pause");
return 0;
}
and my error code
1>------ Build started: Project: bake, Configuration: Debug Win32 ------
1> bake.cpp
1>c:\users\jonbecher\documents\visual studio 2012\projects\bake\bake\bake.cpp(26): error C2084: function 'Squirrel::Squirrel(void)' already has a body
1> c:\users\jonbecher\documents\visual studio 2012\projects\bake\bake\bake.cpp(16) : see previous definition of '{ctor}'
1>c:\users\jonbecher\documents\visual studio 2012\projects\bake\bake\bake.cpp(32): error C2264: 'Squirrel::Squirrel' : error in function definition or declaration; function not called
1>c:\users\jonbecher\documents\visual studio 2012\projects\bake\bake\bake.cpp(33): error C2264: 'Squirrel::Squirrel' : error in function definition or declaration; function not called
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
-
August 9th, 2012, 10:40 AM
#2
Re: Class help using constructors and destructors.
The problem is that you defined the destructor wrongly. You defined it such that it is the default constructor, which was already defined. Rather:
Code:
Squirrel::~Squirrel()
{
cout << "Cleaning up my mess!" << endl;
delete MyDinner;
}
By the way, note that you should define the copy constructor and copy assignment operator too (or declare them private), but I presume that that exercise comes later.
-
August 9th, 2012, 11:31 AM
#3
Re: Class help using constructors and destructors.
Thank you so much! I appreciate the help greatly you resolved the problem for me, and I will be sure to remember that!
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|