Tibor Bujdoš Tibor Bujdoš - 14 days ago 4x
C++ Question

Constructor making object of pointer type

I made this class

class Person {


Person(const std::string& name, const std::string& email, const std::string& city)
: name(name), email(email), city(city) {

bool hasCity() const {
return city.compare("") == 0;

void print() const {
std::cout << name + " <" + email + ">";
std::cout << ", " + city;
std::cout << std::endl;

bool equalTo(const Person& comparedPerson) const {
return email.compare(comparedPerson.email) != 0;

bool equalId(std::string comparedId){
return email.compare(comparedId) != 0;

const std::string name;
const std::string email;
const std::string city;

What is problematic for me is that when i try to create new Person with:

const Person& newPerson = (const Person &) new Person(name, email, city);

i get this error

error: invalid cast of an rvalue expression of type 'Person*' to type 'const Person&'
const Person& newPerson = (const Person &) new Person(name, email, city);

I would like why newly created Person is Person* instead of just Person.


new returns a pointer to object, not an object. Person* instead of Person. Really though, since you tagged this as C++14, you shouldn't be using raw pointers with dynamic allocation.

Just create a variable with automatic storage duration:

Person newPerson(name, email, city);

Or, if you need a pointer, use std::unique_ptr or std::shared_ptr which handles memory management for you:

#include <memory>
auto ptr = std::make_unique<Person>(name, email, city);