C++ Program crash when doing string assign

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
You've forgot to initialize project.
which project? you mean the class?
main.cpp
--------
Line 4: This is an uninitialized pointer.
Line 5: You trying to reference a member function through an uninitialized pointer.


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
closed account (E0p9LyTq)
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");
}


abc
abc
yxz
yxz
Last edited on
Topic archived. No new replies allowed.