Class pointers for c++

Messing about with c++ class pointers I noticed that there are two ways of accessing the class pointer. Using arrow operator or the *dereference.

#include <iostream>
#include "account.h"
#include <string>

int main() {
    //make sure to use the `new` keyword to initialise the class
    account *newname = new account("Ramburn");

    //one method of accessing the class pointer
    std::string x = (*newname).getName();
    std::cout << x << std::endl;

    //method two of accessing the class pointer
    std::string y = newname->getName();
    std::cout << y << std::endl;
    delete newname;

    return 0;
}

Here is the class and header :

//
// Created by bramburn on 18/05/2020.
//

#ifndef TESTABOUT_ACCOUNT_H
#define TESTABOUT_ACCOUNT_H

#include <string>

class account {
//this is default that all methods/attr are private
private:
    std::string name;

//have to explicitly define public methods/attr
public:
    account(const std::string &name);

    std::string getName();
};


#endif //TESTABOUT_ACCOUNT_H
//
// Created by bramburn on 18/05/2020.
//

#include "account.h"

std::string account::getName() {
    return this->name;
}

account::account(const std::string &name) : name(name) {}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.