Jul 18, 2016 at 1:12pm UTC
Hello,
I have a weird problem, this is my code :
test.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#ifndef _test_
#define _test_
#include <iostream>
#include <string>
class Test {
public :
Test();
~Test();
void addName(std::string _Name);
private :
std::string Name;
};
#endif // _test_
test.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "test.h"
Test::Test() {
}
Test::~Test() {
}
void Test::addName(std::string _Name) {
std::cout << _Name << std::endl;
Name = _Name;
std::cout << _Name << std::endl;
}
main.cpp
1 2 3 4 5 6 7 8
#include "test.h"
int main(int argc, char * argv[]) {
Test* project;
project->addName("abc" );
return 0;
}
Results :
abc
The program has unexpectedly finished.
Last edited on Jul 18, 2016 at 1:13pm UTC
Jul 18, 2016 at 1:15pm UTC
You've forgot to initialize project.
Jul 18, 2016 at 1:22pm UTC
which project? you mean the class?
Jul 18, 2016 at 1:56pm UTC
main.cpp
--------
Line 4: This is an uninitialized pointer.
Line 5: You trying to reference a member function through an uninitialized pointer.
Jul 18, 2016 at 1:58pm UTC
project
is a pointer. But it doesn't point to anything - it is uninitialised. You might either make it point to an existing Test
object (at present there isn't one), or create a Test
object using the new
operator.
Last edited on Jul 18, 2016 at 2:00pm UTC
Jul 18, 2016 at 9:20pm UTC
1 2 3 4 5 6 7 8 9 10
#include "test.h"
int main()
{
Test p1;
p1.addName("abc" );
Test* p2 = new Test;
p2->addName("yxz" );
}
Last edited on Jul 18, 2016 at 9:21pm UTC