I have the following code:
[test.h]
class MyClass
{
public:
string Name;
MyClass();
void method(MyClass &obj);
}
[test.cpp]
void MyClass::method(MyClass &obj)
{
cout<<obj.Name<<endl;
}
[main.cpp]
#include "test.h"
void main()
{
MyClass *class = new MyClass();
class->Name="Foo";
class->method(*class);
delete class;
}
I would like to ask if this is the correct way for having method that contain objects send by reference.
Did I correctly deallocate the memory allocated?
I am asking this because for a similar example when testing wit valgrind I have this: conditional jump or move dependents on unitialised value(s).
I am working in c++ under Ubuntu. My compiler is g++.
APPRECIATE!!
EDIT!!
WHY CAN’T I PUT INT VALUE=0; in the test.h file?!
If
VALUEis part of class variables, then it is not allowed to initialize as a part of class declaration. Instead, constructor initializer list should be used.How ever, if
VALUEis defined as a global variable then this too leads to problems. When you includetest.hin multiple source files, it leads to multiple declaration errors. Define it in a source file and access across multiple translation units using the extern key word.