Tjatte Tjatte - 1 month ago 7
C++ Question

C++ How to access the dynamical objects attributes

in my code, i've got two different objects. One "normal" object and one dynamical object:

1.)

Person firstPerson("Bernd",22);


2.)

Person* secondPerson = new Person("Andria", 33);


Now i want to create a method that can print the objects values (Name, Age) on the console. The Method below is working for the first object(1.) but not for the second object (2.):

void Person::printData(){
std::cout << "Name: " << Person::getName() << " ; Age: " << Person::getAge() << "." << std::endl;
}


How do i access the attributes of a dynamical created object? I know that i have to use "->" but i dont know how.
And is there a way to create only one method that is working for both methods?
Like:

firstPerson.printData();
secondPerson.printData();


Thanks in advance

Answer

Since secondPerson is a pointer do this: secondPerson->printData();