0

I have a weird problem, this is my code :

test.h

#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

#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

#include "test.h"
int main(int argc, char* argv[]) {
    Test* project;
    project->addName("abc");
    return 0;
}

Results :

abc

The program has unexpectedly finished.

Tyranitar
  • 37
  • 1
  • 7
  • 2
    Why are you declaring `project` as a pointer? I suggest you get rid of it being a pointer and the code should work fine after changing `->` to `.`. – NathanOliver Jul 18 '16 at 14:01
  • 1
    Totally unrelated to your problem, but [don't use leading underscore followed by an upper-case letter, such symbols are reserved in all scopes](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – Some programmer dude Jul 18 '16 at 14:04
  • Why did you choose to declare your object as a pointer? –  Jul 18 '16 at 14:17

2 Answers2

6

That's because you have a pointer to a Test object, but it doesn't actually point anywhere. That leads to undefined behavior when you try to dereference the pointer.

Declare the object as an actual object, not a pointer:

Test project;
project.addName("abc");
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

The pointer project is default-initialized and has indeterminate value, so dereferencing it has a big chance to cause abnromal termination of the program.

Try creating an object and assigning it before dereferencing like this:

#include "test.h"
int main(int argc, char* argv[]) {
    Test* project = new Test;
    project->addName("abc");
    delete project;
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70