The problem is that the pointer named tag1
has not been initialized. And you're dereferencing this uninitialized pointer when you wrote tag1->tag_name = "tag1";
which leads to undefined behavior.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
For example, here the program crashes but here it doesn't crash.
Solution
To solve this you you have make sure that this pointer points to some tag
type object. For example,
class tag {
public:
std::string tag_name;
tag* child;
};
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
//create object of type tag
tag obj;
obj.tag_name = "original tag";
std::cout<<obj.tag_name<<std::endl;
//create pointer to object obj
tag* tag1 = &obj;
tag1->tag_name = "tag1";
std::cout<<tag1->tag_name;
return 0;
}
Demo
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.