lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Is it OK use "this" for Structure

Sat Dec 26, 2015 9:36 pm

struct Object
{
string objstring;

}

void Object::funct (...)
{

this->objstring=" this is a test";
}


Can I treat the structure like a class?

User avatar
AndyD
Posts: 2334
Joined: Sat Jan 21, 2012 8:13 am
Location: Melbourne, Australia
Contact: Website

Re: Is it OK use "this" for Structure

Sat Dec 26, 2015 10:50 pm

Yes, in C++ a struct and a class are treated the same. The difference is that by default (if you don't specify an access modifier [public:, private:, protected:]) member functions and variables in a struct are public, while in a class by default member function and variables are private.

However, mostly there is no need to access member variables and functions in C++ using the this pointer. It is common to distinguish member variable using some sort of naming convention (For example using a trailing underscore objstring_) and so there should be no ambiguity between parameters passed into a member function and member variables. The this pointer is used significantly in operator overloading (for instance in the assignment "=" operator).

User avatar
PeterO
Posts: 5880
Joined: Sun Jul 22, 2012 4:14 pm

Re: Is it OK use "this" for Structure

Sat Dec 26, 2015 10:54 pm

http://stackoverflow.com/questions/4791 ... t-vs-class
Google really is your friend !
PeterO
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

Return to “C/C++”