I was looking at a library a person has made for FaceBook in C++. The header file is this:
#ifndef __FACEBOOK_H__
#define __FACEBOOK_H__
/**
* Facebook Class
* Joel Seligstein
* Last mod: Aug 22, 2006
*
* This is the beginnings of a facebook class set and REST client. Its not documented
* yet nor nearly complete. But this is a release to demonstrate its usefulness.
* Please email joel#seligstein.com with suggestions or additions.
*
* TODO: Create classes/parsers for each request type
* TODO: Linux URL launcher
*/
//uncomment to have verbose output turned on
//#define fb_debug 1
//define which platform you're compiling for
#define fb_windows 1
//#define fb_linux 1
#include <string>
#include <sstream>
#include <list>
using namespace std;
#ifdef fb_windows
#include <windows.h>
#endif
#include "curl/curl.h"
#include "xmlParser/xmlParser.h"
#include "md5.h"
class facebook
{
public:
//app/session vars
string api_key;
string secret;
string token;
string server;
string session_key;
string session_secret;
string uid;
bool has_session;
facebook( string my_key, string my_secret, string my_server );
bool authenticate( );
bool request( string method, list<string> params, string *res );
bool load_token( );
void launch_login( string url );
bool get_session( );
void clean_up( );
private:
//curl info
CURL *curl;
CURLcode res;
int call_id;
//internal functions
string get_signature( list<string> params );
static string md5( string str );
static string get_param_string( list<string> params, bool separate );
static size_t write_callback( void *ptr, size_t size, size_t nmemb, void *userp );
};
#endif //__FACEBOOK_H__
Then inside the cpp file, my question is regarding this, the below is the constructor:
facebook::facebook( string my_key, string my_secret, string my_server )
{
this->api_key = my_key;
this->secret = my_secret;
this->server = my_server;
this->has_session = false;
this->call_id = 0;
}
Why have they used the -> operator and not .?
I have a limited understanding that -> accesses properties and methods of the type directly in memory but I am confused, I would, through ignorance, expect to see:
facebook::facebook( string my_key, string my_secret, string my_server )
{
this.api_key = my_key;
this.secret = my_secret;
this.server = my_server;
this.has_session = false;
this.call_id = 0;
}
All I want to know is the theory behind why -> is used over the dot notation.
UPDATE:
For anyone else in the same boat as me and learning C++. I have expanded on an example posted by a member in this question. I have also wrapped in initialization list for a member field.
#include "stdafx.h"
#include <iostream>
using namespace std;
class A {
private:
int x;
public:
A() : x(0){}
int getX() const {return x;}
void setX(int xx) {x += xx;}
};
int main()
{
A a;
a.setX(13);
A *pa = &a;
pa->setX(2);
A b = a;
b.setX(5);
cout << "a" << a.getX() << endl;
cout << "a*" << pa->getX() << endl;
cout << "b" << b.getX() << endl;
return 0;
}
this is a pointer to the current object i.e., inside methods (or constructor) of class A, this is of type A *.
(Note that, if the method is tagged as const, this is of type A const *.)
Hence the use of -> (designed only for pointers) and not . (designed only for class objects A or references to class objects A&).
In C++, this is a pointer to the self object. It's a relic leftover from early versions of C++, before it had references. If this were added to the language now, it probably would be a reference, for which you'd use the . notation.
Because inside a class or struct member, "this" is a special pointer that points to the current instance.
Any time you're accessing members of a class or struct through a pointer, the -> operator is used.
If you're accessing them through anything that isn't a pointer (usually a reference), the dot operator is used instead.
It's worth noting that the this-> syntax isn't necessary except in some forms of template instanciation. A lot of people choose to use it for stylistic reasons, though. There are a couple questions related to rationale behind this on S.O. already.
You may consider the following example.
class A {
int x;
public:
int getX() const {return x;}
void setx(int xx) {x = xx;}
};
int main()
{
A a;
a.setX(13);
cout << a.getX() << endl;
A *pa = &a;
cout << pa->getX() << endl;
return 0;
}
Notice that, dot operator (.) is used when calling a member function of A directly with the object a. The arrow operator (->) is used when calling a member function of A indirectly through a pointer of type A (A *pa = &a).
In C++, this is a pointer to the invoking object. Thus we could also define A::getX() function as follows:
int getX() const {return this->x;}
Or:
int getX() const {return (*this).x;}
this is a pointer of object A, thus *this dereferences it. So we could use both of the functions above.
As said, this is a pointer and not a reference. Thus you need the -> operator that is roughly (while not exactly the same as): (*this).
They differ in that you can overload -> operator or * operator in a class and can have different semantics. As a matter of fact, if a class overrides operator-> and the returned value is not a raw pointer, the compiler will keep on applying operator-> to the returned object until it reaches a native pointer. Operator . cannot be overloaded.
In the constructor you pointed, the use of this is completely optional as there is no name collision the code could just have named the attributes without further qualification.
facebook::facebook( string my_key, string my_secret, string my_server )
{
api_key = my_key;
secret = my_secret;
server = my_server;
has_session = false;
call_id = 0;
}
And a better solution would be using an initialization list. If you are interested in learning C++ google for it.
because "this" is a special pointer that refers to the current object and we use "->" to access the members of the object through pointers and "." is used for calling the member of a object directly.
Related
I am learning to use void pointers. Here I have created a resource class which can store any type of structure in (void *) and now when I try to get that structure back in (void *), I am not able to get same data back. Please help here
#include <iostream>
using namespace std;
class resource{
private:
void* data;
public:
void set(void* val){
data = val;
}
void get(void* val){
val = data;
}
};
class student{
struct st{
int id;
int age;
};
public:
void func(){
st *st1 = (st *)malloc(sizeof(st));
st1->id = 5;
st1->age = 10;
resource *rsrc = new resource();
rsrc->set((void*)st1);
void *data;
rsrc->get(&data);
st *st2 = (st*)data;
cout<<"get data %d"<<st2->id<<endl; // HERE I want to get same data back
}
};
int main() {
student *stu = new student();
stu->func();
return 0;
}
Just change the signature of get to return a void *:
void *get(){
return data;
}
And subsequently:
void *data = rsrc->get();
Also, it is idiomatic to use new, rather than malloc, to construct objects, although for POD (plain-old-data) types, either is valid.
Your get method won't return any value. You are passing a void pointer to it and inside the method, you overwrite that void pointer. However, that only overwrites the local copy of the void pointer and does not return a value. As others stated, you either have to pass a pointer to a pointer or use the return statement to return the value of the pointer.
In your specific case, #PaulSanders made the correct suggestion. You should use the getter/setter pattern. Also, he is correct that you should use new and delete in idomatic C++.
For user-created classes, most people specify classes with the first letter as a captial:
class Resource {};
class Student {};
It depends on your coding standard. It matters less whether you use camel case or not so long as you use a consistent naming convention.
Also, we generally try to prevent loss of type information in C++. Of course, you can use a C-style cast which will just reinterpret the pointer as the specified type but that is considered bad style and likely to cause problems.
I am working on my first separate class file. I have been given a driver program which I am not supposed to change and I am to create a class file that runs off the driver.
#include <iostream>
#include <iomanip>
using namespace std;
#include "Question.h"
int main()
{
string q2Answers [] = {"China","India","Mexico","Australia"};
Question q2("Which country is home to the Kangaroo?",q2Answers,'D');
q2.display();
cout << endl;
}
The driver, simplified above, appears to be passing arguments to the class via arguments. My class header file is built in the following fashion.
#ifndef QUESTION_H
#define QUESTION_H
#include <string>
using namespace std;
class Question
{
public:
void setStem(string newStem);
void setAnswers(string newAnswers[]);
void setKey(char newKey);
void display();
string getStem();
string getAnswer(int index);
char getKey();
private:
string stem;
string answers[4];
char key;
};
#endif // QUESTION_H
How can I execute the functions in my class using arguments passed into an object? I am confused as to how the line,
Question q2("Which country is home to the Kangaroo?",q2Answers,'D');
has any way of pushing those arguments into the functions. Any insight into this would be very appreciated.
If I understood you correctly, you're asking for how to make a constructor(See OldProgrammer's link in the comment to your question):
You can either make it right in the header file, like so:
Question(const std::string& theQuestion,
const std::string theOptions[], const char& correctAnswer)
{
this->stem = theQuestion;
for(int i=0; i<4; i++){
this->answers[i] = theAnswers[i];
}
this->key = correctAnswer;
}
~Question(){}
//This is called the "Destructor", it is a function called when the object is destroyed
(You can imagine the const std::string&-part as string or const char&-part as just char if you don't know what they mean, since it's not very important right now.)
Or you can make it in the separate .cpp-file like so:
Question::Question(const std::string& theQuestion,
const std::string& theOptions[], const char& correctAnswer)
{
this->stem = theQuestion;
for(int i=0; i<4; i++){
this->answers[i] = theAnswers[i];
}
this->key = correctAnswer;
}
Question::~Question(){}
You might be asking why we use destructors; it's because sometimes there are things we need to do before the object is removed.
Like for instance if you want to save certain info or make a change, or more commonly to free dynamic memory you allocated when you made the object. Otherwise you get memory leaks, which are bad.
Then you can construct/create an object as such:
Question q2("Which country is home to the Kangaroo?",q2Answers,'D');
You can also "overload" the constructor, i.e. you can make other versions of it. For example if you imagine that the constructor's only parameter was the question:
Question(std::string q){
this->stem = q;
}
Question(char c[]){
this->stem = c;
}
Now you can pass either a string or an array of characters to the object. But if you only have one, you can't do the other too, so if we only have the first constructor, we can't pass an array of characters to do the exact same thing. And you can make as many of these as you like, but it doesn't necessarily mean that it's better just because it has a ton of constructors.
I am trying to make a map which stores a string as an identifier and a function that returns a string i have tried typedef but i kept running into problems because i couldn't convert my typedef string (command)() to a regular string i have also tried map commands but it gives me an expression expected error but it does work if i replace string with int. Does anybody know a way of doing this? This is what my code looks like
#include "iostream"
#include <map>
#include <functional>
using namespace std;
class GameController {
public:
void inputReader();
private:
bool gameOver = false;
map<string,string(*)()> commands;//Does not work
//commands
string commandReader(string* inputCommand);
void initCommands();
//both
char* end();
string run();
//while attacking
string attack();
string usePotion();
string useItem();
//while in room
string engage();
string searchRoom();
string rest();
string checkBag();
string checkMap();
string checkStats();
//string save();
};
#endif //ROGUE_GAMECONTROLLER_H
#include "GameController.h"
GameController::GameController(){
initCommands();
}
void GameController::inputReader() {
while (!gameOver){
string x;
getline(cin,x);
cout << commandReader(&x) << endl;
}
}
string GameController::commandReader(string *inputCommand) {
for (map<string,string>::iterator it = commands.begin(); it!=commands.end(); ++it)
{
if(it->first == *inputCommand)
{
return it->second;
}
}
return "Computer says no type help for commands";
}
void GameController::initCommands() {
commands["end"] = end;
//while attacking
commands["run"] = run;
commands["attack"] = attack;
commands["use potion"] = usePotion;
commands["use item"] = useItem;
//while in room
commands["engage"] = engage;//TODO
commands["search"] = searchRoom;
commands["rest"] = rest;
commands["check bag"] = checkBag;
commands["map"] = checkMap;
commands["stats"] = checkStats;
}
This question is tagged C++11, so here's a concise example which uses unordered_map (a real hash map, unlike std::map which my STL reference says is commonly implemented using binary search trees), and std::function.
#include <iostream>
#include <functional>
#include <string>
#include <unordered_map>
std::string foo()
{
return "foo!";
}
struct MyClass
{
static std::string bar()
{ return "bar!"; }
std::string FizzBuzz() const
{ return "FizzBuzz!"; }
std::string operator()() const
{ return "Myclass!"; }
};
int main(int argc, char **argv)
{
MyClass mc;
std::unordered_map<std::string, std::function<std::string()>> commands;
commands["myfoo"] = foo;
commands["mybar"] = MyClass::bar;
commands["myfb"] = std::bind(&MyClass::FizzBuzz, mc);
commands["myclass"] = mc;
for( const auto &f : commands)
std::cout << f.second() << std::endl;
std::cout << commands["myfoo"]() << std::endl;
return 0;
}
Pointers to member functions is not like pointers to free functions or even static methods. For one thing all member functions have a hidden this pointer in the function parameters that makes all of this object magic work.
Going through step by step:
First, define a helper:
typedef string (GameController::*funcp)();
This defines type funcp which represents a pointer to a member function of GameController (to partly take care of the this problem) that takes no parameters and returns string
Then, modify your map to use funcp
map<string, funcp> commands;
Then you have to change the assignment of the member functions a bit to be brutally explicit that it is a pointer and a member of GameController
commands["end"] = &GameController::end;
You can also save yourself some runtime trouble and use an initializer list here rather than a function and a map in every single GameController object. That'll take a bit of extra explaining and I have to be on the move in a few minutes. Sorry about that. A static map with static initializing really is better and worth your time researching, though.
The next bit I stole from the C++ Super FAQ. Read this link. Worth reading all of it, because it heads off a lot of the question you will have.
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))
This makes calling the function awesomely easy.
return CALL_MEMBER_FN(*this, it->second)();
And that should about do it for you.
edit:
Tweej demonstrates the generally better way to do this, std::function and std::bind, in their answer. Since I'm advocating the ancient ways, I'd like to explain why.
Two reasons: one is tunnel vision directly answering OP's question.
The second is With the ancient ways I could easily make commands static and save having to create a new copy of commands for every instance of GameController. When using std::bind, you have to have the bound object, and that ruins the static idea.
Poking around at the idea of just using std::function seems to have born fruit and rendered obsolete the ancient ways. gone is the CALL_MEMBER_FN macro. Gone is the funcp typedef
The map is now defined as static, what I was aiming for the the old-pre C++11 approach. Note the funcp typedef is replaced by a function that takes a pointer to GameController to supply this.
static map<string, std::function<string(GameController*)>> commands;
And the map is now rigged to use a static initializer list. No function required. This initializer needs to sit outside the class definition because... I'm not sure why. I think this is changed in C++14.
map<string, std::function<string(GameController*)>> GameController::commands
{
{"end", &GameController::end},
{"run", &GameController::run},
{"attack", &GameController::attack},
{"use potion", &GameController::usePotion},
{"use item", &GameController::useItem},
{"engage", &GameController::engage},
{"search", &GameController::searchRoom},
{"rest", &GameController::rest},
{"check bag", &GameController::checkBag},
{"map", &GameController::checkMap},
{"stats", &GameController::checkStats}
};
The map is initialized once and only once. All GameControllers will use the same commands, so the constructor is really dumb
GameController::GameController()
{
// init function is gone
}
Command reader gets a big rip-up, mostly because the point of a map is you can search it by the key. So I search for the key rather than iterating. The function call is now obvious and dead simple:
string GameController::commandReader(const string &inputCommand)
{
map<string, std::function<string(GameController*)>>::iterator found = commands.find(inputCommand);
if (found != commands.end())
{
return found->second(this);
}
return "Computer says no type help for commands";
}
This is my first question:
I am trying to read "global attributes" from a NetCDF file (using the C++ legacy API). By "global attribute" I mean an attribute that was added to a NcFile, not to a NcVar.
For most things the "Example netCDF programs" are useful -- but there is no example for "global attributes".
Consulting the "netcdfcpp.h" I find a few things:
NcFile has a member function: NcAtt* get_att(NcToken) const;
NcAtt has NO public constructor
NcAtt is friends with NcFile: friend class NcFile;
NcAtt has a private constructor: NcAtt( NcFile*, NcToken);
NcAtt has a public member function NcValues* values( void ) const;
NcValues has an API defined through the ncvalues.h header
My coding skills are insufficient to understand how I get back at the string/int/float stored as NcValue, in an NcAtt class within NcFile.
Attached is a example code of my problem "NetCDF_test.cpp", with the critical part missing from the implementation of the "LoadNetCDF" function.
The code compiles OK with: (edit: also, "TestFile.nc" is created correctly)
g++ -c NetCDF_test.cpp -o NetCDF_test.o
g++ -o NCTEST NetCDF_test.o -lnetcdf_c++ -lnetcdf
Example code:
#include <iostream> // provides screen output (i.e. std::cout<<)
#include <netcdfcpp.h>
struct MyStructure {
std::string MyString;
int MyInt;
float MyFloat;
MyStructure(); // default constructor
int SaveNetCDF(std::string); // Save the struct content to "global attributes" in NetCDF
int LoadNetCDF(std::string); // Load the struct content from "global attributes" in NetCDF
};
MyStructure::MyStructure(void)
{
MyString = "TestString";
MyInt = 123;
MyFloat = 1.23;
}
int MyStructure::SaveNetCDF(std::string OUTPUT_FILENAME)
{
NcError err(NcError::silent_nonfatal);
static const int NC_ERR = 2;
NcFile NetCDF_File(OUTPUT_FILENAME.c_str(), NcFile::Replace);
if(!NetCDF_File.is_valid()) {return NC_ERR;}
if(!(NetCDF_File.add_att("MyString",MyString.c_str()))) {return NC_ERR;}
if(!(NetCDF_File.add_att("MyInt",MyInt))) {return NC_ERR;}
if(!(NetCDF_File.add_att("MyFloat",MyFloat))) {return NC_ERR;}
return 0;
}
int MyStructure::LoadNetCDF(std::string INPUT_FILENAME)
{
NcError err(NcError::silent_nonfatal);
static const int NC_ERR = 2;
NcFile NetCDF_File(INPUT_FILENAME.c_str(), NcFile::ReadOnly);
if(!NetCDF_File.is_valid()) {return NC_ERR;}
// ???? This is where I am stuck.
// How do I read the global attribute from the NetCDF_File ??
return 0;
}
int main()
{
std::cout<< "START OF TEST.\n";
MyStructure StructureInstance; // datamembers initialized by constructor
StructureInstance.SaveNetCDF("TestFile.nc");
StructureInstance.MyString = "Change string for sake of testing";
StructureInstance.MyInt = -987;
StructureInstance.MyFloat = -9.87;
StructureInstance.LoadNetCDF("TestFile.nc"); // data members are supposed to be read from file
std::cout<< "Now the data members of StructureInstance should be TestString, 123, and 1.23\n";
std::cout<< StructureInstance.MyString << " ; " << StructureInstance.MyInt << " ; " << StructureInstance.MyFloat <<"\n";
std::cout<< "END OF TEST.\n";
}
It's pretty clearly spelled out in the C++ users guide: http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-cxx/Class-NcAtt.html#Class-NcAtt
"Because attributes are only associated with open netCDF files, there are no public constructors for this class. Use member functions of NcFile and NcVar to get netCDF attributes or add new attributes."
global attributes are attributes on the file (as opposed to variable attributes which are, well, attributes on the variable)
NetCDF_File.num_atts() returns how many global attributes. The get_att() methods (overloaded in various ways) will get you an attribute.
consult http://www.unidata.ucar.edu/software/netcdf/docs/netcdf-cxx/Class-NcFile.html#Class-NcFile
Many thanks to Rob Latham for the links to a commented description of the NetCDF API (legacy C++). With the information given there I was able to figure it out:
NcAtt inherents form NcTypedComponent a set of member functions for accessing data stored within a given NcAtt: (int n == n-th element)
ncbyte as_ncbyte( int n ) const
char as_char( int n ) const
short as_short( int n ) const
int as_int( int n ) const
nclong as_nclong( int n ) const // deprecated
long as_long( int n ) const
float as_float( int n ) const
double as_double( int n ) const
char* as_string( int n ) const
But still, the constructor for NcAtt is private and the only access point to an existing NcAtt is through the NcFile member function NcVar* get_var(NcToken name) const -- which only returns a pointer. Hence the straight forward usage does not work:
int MyInt = MyNcFile.get_att("MyInt").as_int(0); // DOES NOT COMPILE
However, dereferencing the pointer returned by get_att does the trick.
int MyInt = (*MyNcFile.get_att("MyInt")).as_int(0); // WORKS
For sake of completeness I include below the implementation of MyStructure::LoadNetCDF for the example code of my original question.
int MyStructure::LoadNetCDF(std::string INPUT_FILENAME)
{
NcError err(NcError::silent_nonfatal);
static const int NC_ERR = 2;
NcFile NetCDF_File(INPUT_FILENAME.c_str(), NcFile::ReadOnly);
if(!NetCDF_File.is_valid()) {return NC_ERR;}
// NcAtt constructor is private, but one can obtain the pointer to an existing NcAtt
NcAtt* PointerToMyIntNcAtt = NetCDF_File.get_att("MyInt");
// Now, using the dereferencing operator one has access to the member functions that NcAtt inherents from NcTypedComponent
if(!(*PointerToMyIntNcAtt).is_valid()) {return NC_ERR;}
std::cout<< "Is MyInt a valid NcAtt? "<< (*PointerToMyIntNcAtt).is_valid()<<"\n";
// The concise way of writing the access to NetCDF "global attributes"" of type int/float/string
MyInt = (*NetCDF_File.get_att("MyInt")).as_int(0);
MyFloat = (*NetCDF_File.get_att("MyFloat")).as_float(0);
MyString = (*NetCDF_File.get_att("MyString")).as_string(0);
return 0;
}
Suppose I have a class:
class test {
public:
void print();
private:
int x;
};
void test::print()
{
cout<< this->x;
}
and I have these variable definitions:
test object1;
test object2;
When I call object1.print() this happens to store address of object1 and so I get x from object1 printed and when I call object2.print() this happens to store address of object2 and I get x from object2 printed. How does it happen?
Each non-static member function has an implicit hidden "current object" parameter that is exposed to you as this pointer.
So you can think that for
test::print();
there's some
test_print( test* this );
global function and so when you write
objectX.print();
in your code the compiler inserts a call to
test_print(&objectX);
and this way the member function knows the address of "the current" object.
You can think of the this pointer being an implicit argument to the functions. Imagine a little class like
class C {
public:
C( int x ) : m_x( x ) { }
void increment( int value ) {
m_x += value; // same as 'this->m_x += value'
}
int multiply( int times ) const {
return m_x * times; // same as 'return this->m_x * times;'
}
private:
int m_x;
};
which allows you to write code like
C two( 2 );
two.increment( 2 );
int result = two.multiply( 3 );
Now, what's actually happening is that the member functions increment and multiply are called with an extra pointer argument, pointing to the object on which the function is invoked. This pointer is known as this inside the method. The type of the this pointer is different, depending on whether the method is const (as multiply is) or not (as is the case with increment).
You can do something like it yourself as well, consider:
class C {
public:
C( int x ) : m_x( x ) { }
void increment( C * const that, int value ) {
that->m_x += value;
}
int multiply( C const * const that, int times ) const {
return that->m_x * times;
}
private:
int m_x;
};
you could write code like
C two( 2 );
two.increment( &two, 2 );
int result = two.multiply( &two, 3 );
Notice that the type of the this pointer is C const * const for the multiply function, so both the pointer itself is const but also the object being pointed to! This is why you cannot change member variables inside a const method - the this pointer has a type which forbids it. This could be resolved using the mutable keyword (I don't want to get side-tracked too far, so I'll rather not explain how that works) but even using a const_cast:
int C::multiply( int times ) const {
C * const that = const_cast<C * const>( this );
that->m_x = 0; // evil! Can modify member variable because const'ness was casted away
// ..
}
I'm mentioning this since it demonstrates that this isn't as special a pointer as it may seem, and this particular hack is often a better solution than making a member variable mutable since this hack is local to one function whereas mutable makes the variable mutable for all const methods of the class.
The way to think about it is that this is simply a pointer to the memory for whichever object you're currently working with. So if you do obj1.print(), then this = &obj1;. If you do obj2.print(), then this = &obj2;.
this has different values for different objects
Each instance of class test gets it's own copy of member variable x. Since x is unique for each instance, the value can be anything you want it to be.
The variable this, refers to the instance to which it is associated. You don't have to use the variable 'this'. You could just write:
void test::print()
{
cout << x;
}