mardi 20 juillet 2021

Returning the value of a class member pointer variable using 'this' pointer

My scenario is , I want to return the value of class member variable m_ptr using this pointer.

What I have tried is ,

#include <iostream>

using namespace std;

class Test{
    int *m_ptr;
    
    
    public:
        Test():m_ptr(nullptr){
            cout<<"Def constr"<<endl;
        }
        
        Test(int *a):m_ptr(a){
            cout<<"Para constr"<<endl;
        }
        
        ~Test(){
            cout<<"Destr "<<endl;
            delete m_ptr;
        }
        
        int getValue(){
            return *m_ptr;
        }

};

int main(){
    
    Test obj(new int(34));
    cout<<"Value -"<<obj.getValue()<<endl;
    return 0;
}

The console output is

Para constr
Value -34
Destr

This is fine.

What I am trying to do now is ,

I want to modify the getValue function to return the value of pointer variable m_ptr using this pointer like below . (only writing the getValue function)

int getValue(){
    return this->(*m_ptr);
} 

But this throws the error as,

[Error] expected unqualified-id before '(' token

I am beginner in this c++ and I am not understanding the actual reason for this error. It will be helpful to explain what I am doing wrong here.

Aucun commentaire:

Enregistrer un commentaire