Initializing an object using a string

I am trying to initialize an object by passing it a string, and initialzing it to a member variable called 'name'. However, when I try to access name through the pointer to the object, there is nothing there. Do I need to use pointers and references to achieve this?

1
2
3
4
5
6
7
8
9
10
11
// main.cpp

#include "carouselItem.h"

//========================================================================
int main( ){
    string one = "One";
    CarouselItem *fp1 = new CarouselItem(one);  
    cout << "Name: " << fp1->name << endl;
}


1
2
3
4
5
6
7
8
9
10
11
12
// carouselItem.h

#import <string>

class CarouselItem {
public:    
    CarouselItem(string name);

    string name;    
};

#endif 


1
2
3
4
5
6
7
8
9
// carouselItem.cpp

#include <iostream>
#include "carouselItem.h"

CarouselItem::CarouselItem(string name)
{
    name = name;
}


The problem is probably with this:
name=name;
Give the argument a different name.
(And it is recommended to use the initialization list syntax in this scenario.)
name = name; name refers to the parameter so name is just assigned to itself. Use this->name to refer to the member name.
1
2
3
4
CarouselItem::CarouselItem(string name)
{
	this->name = name;
}


Or use the initialization syntax
1
2
3
4
CarouselItem::CarouselItem(string name)
:	name(name)
{
}
Thanks guys, I've amended it to use the initialization list syntax and it works great.
Topic archived. No new replies allowed.