Assignment Operator Overloading not invoking when accessing through pointers [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I have an issue on operator overload in C++, Consider the following class
CharacterString.h file
class CharacterString {
private:
char* __charString;
public:
CharacterString();
~CharacterString();
void operator =(const char* sFileName);
};
//CharactorString.cpp file
CharacterString::CharacterString() { }
CharacterString::~CharacterString() { }
void CharacterString::operator=(const char* sFileName)
{
this->__charString = (char *)sFileName;
}
In the main function, the following code works fine.
CharacterString fileName;
fileName = "Hello, World";
However, the bellow code causing shows compiler error
CharacterString* fileName;
fileName = new CharacterString();
fileName = "Hello, World";
printf("%s", fileName);
enter image description here

If you declare fileName as a pointer:
CharacterString* fileName;
Then if you want to access the object, you must first dereference it by using * or -> so:
*fileName = "Hello, World";
fileName->operator=("Hello, World");
The printf() call is completely incorrect and it works only by accident (because CharacterString object is put on the stack in the same binary format as char *). You should add a getter method for string:
class CharacterString {
private:
char* __charString;
public:
CharacterString();
~CharacterString();
char *getString() { return __charString; }
void operator =(const char* sFileName);
};
Then you can write:
printf("%s", fileName->getString());
Try to make e.g. ~CharacterString() virtual to change the binary representation of the object and immediately it stops working without getString().
Last (off topic), please note that symbols starting with underscores are reserved and should not be used in "user code".

Related

String in a class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was working on a project and I've had a question: when I call a class that contain a string str, does the code create a string every time or it use the string I've already created?
For example:
#include <iostream>
using namespace std;
class exClass {
public:
void exVoid ( string valueStr )
{
str = "Hi";
cout << str;
}
private:
string str;
};
int main()
{
exClass myClass;
string stringMain;
while (1)
{
cout << "Insert value of str: ";
cin >> stringMain;
myClass.exVoid(stringMain);
}
}
so the question is: every time I call exClass, the class create the string str or it do that only once (when I call it for the first time)?
Following the flow of the program:
First you create an instance of exClass named myClass. This happens once.
Then you create a string named stringMain. This also happens once.
After that, you have an endless loop while(1). Inside this loop you:
Print on the output
Get input
Call function exVoid()
So, you create one instance of class exClass with one member str and use the same str (through your function) endlessly inside your loop.
Something to think about is the function argument. You never really use it. For it to have meaning in you code, you can do something like:
void exVoid ( string valueStr )
{
str = valueStr;
cout << str;
}
Yes, you're creating a copy of your input string every time you call exVoid. You can make it more efficient if you use a reference:
void exVoid(const std::string &value) {
...
}
The way you're calling it from main, you're thus passing a reference to stringMain, but by making it const, you know your method won't mess with it.

Function, that creates other functions c++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I have a task to create function Factory(const std::string name) that returns pointer to function without arguments that prints name. Also I should use only native language methods (without lambda functions and etc). Could you give me example?
Annotations in the code. I deliberately did not make it print to std::cout directly but instead it will return the string. Adapt it as you please.
#include <iostream>
struct bork { // the object to hold the text to return
std::string text; // the text to return
// constructor
bork(const std::string& in) : text(in) {}
// the operator that makes the object behave like a function
std::string operator ()(void) const { return text; }
// a factory method to create a "bork"
static bork make_bork(const std::string& text) {
return bork(text);
}
};
int main() {
auto a = bork::make_bork("howdy");
auto b = bork::make_bork("world");
std::cout << a() << "\n";
std::cout << b() << "\n";
}
You cannot create a function in a function. The only way is to know all the strings there will appear and having a functions for each possible string, and then select and return the proper function. Or else you can use objects :-)

How to call pointer to member function, which has been saved in a vector of custom struct? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
My question is actually regarding already asked question. I have tried the answer given by #r3mus n0x also have seen some SO questions which did not help me to get a clear idea about the above situation.
In the given post lacks MCVE, therefore I have tried a bit and came up with the following code and with the same error what #user10213044 mentioned in his/her post.
Error msg
error C2065: 'm_func': undeclared identifier
My qestion:
Q1: Can we really store the pointer to some of the member functions of a class(like in the following example) into it's on private member(ex. vector array)? If so what is the reason for the above error msg?
Q2: I have also tried to write inside the for loop:
classFuncPtr fun = bindClassPtr->m_func; // compiles
fun(str); // error
gave me: Error msg
error: must use '.*' or '->*' to call pointer-to-member function in 'fun (...)', e.g. '(... ->* fun) (...)'
fun(str); // error
which I could not understand. Can anybody tell me what went wrong in this case?
The second attempt was similar to the following case which we use for normal functions pointer case.
typedef void(*FuncPtr)(const std::string&);
FuncPtr Lambda = [](const std::string& str) { std::cout << str << std::endl; };
Lambda(std::string("Hellow World"));
Here is the code I tried:
#include <iostream>
#include <vector>
#include <string>
#include <memory>
class MyClass;
typedef void (MyClass::*classFuncPtr)(const std::string&); // function ptr to MyClass::member functions
struct MyBind // bind struct
{
classFuncPtr m_func;
explicit MyBind(const classFuncPtr& func): m_func(std::move(func)) {}
};
class MyClass
{
std::string m_var;
std::vector<std::unique_ptr<MyBind>> my_binds_;
public:
MyClass() // constructor
{
my_binds_.emplace_back( std::make_unique<MyBind>( std::move(&MyClass::do_this) ));
my_binds_.emplace_back( std::make_unique<MyBind>( std::move(&MyClass::do_that) ));
}
// two functions to bind
void do_this (const std::string& str) { std::cout << "From do this: " << str << std::endl; }
void do_that (const std::string& str) { std::cout << "From do that: " << str << std::endl; };
void handle_input(const std::string& str)
{
for (const std::unique_ptr<MyBind>& bindClassPtr: my_binds_)
{
// how to print passed string str here?? (Q1)
(bindClassPtr->*m_func)(str);
/*
classFuncPtr fun = bindClassPtr->m_func; // compiles (Q2)
fun(str); // error
*/
}
}
};
Your first attempt fails because there's no variable in scope named m_func.
Your second attempt fails because a pointer-to-member requires an object to be called on.
The correct syntax is:
classFuncPtr fun = bindClassPtr->m_func;
(this->*fun)(str);
Live Demo
The pointer contained in your MyBind objects isn't actually bound to anything. It's a pointer to a member of MyClass, so you have to provide it an instance of MyClass to work on.

"inString not declared in this scope" [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
Working on an implementation of the Shunting Yard algorithm and I keep getting this error (In function 'void InputString()': 'inString was not declared in this scope') when trying to compile (what little) code I have - not entirely sure what could be causing it.
#include <iostream>
#include <string>
#include <stack>
#ifndef SHUNTINGYARD_H
#define SHUNTINGYARD_H
class ShuntingYard {
public:
void InputString();
void OutputString();
int precedence(char A, char B);
void ShuntingAlgorithm();
private:
std::string inString;
std::string outString;
std::stack<char> operatorStack;
std::stack<char> tokenStack;
};
#endif // SHUNTINGYARD_H
void InputString() {
std::cout << "Please enter an expression: ";
std::cin >> inString;
}
I'm sure I'll feel really dumb when I find/someone explains the solution, but I can't figure it out at the moment.
when you do -
void InputString() {
std::cout << "Please enter an expression: ";
std::cin >> inString;
}
It is only a bare function and it is not a member of the class ShuntingYard.
Hence it is not recognizing "instring"
So make InputString as a member of the class and then define it like below-
void ShuntingYard::InputString() {
std::cout << "Please enter an expression: ";
std::cin >> inString;
}
NOTE: Always write #endif //SHUTTINGYARD_H at the end of the file. It makes your code more standard.
Try adding the class name as well as the :: operator before the function's implementation:
void ShuntingYard::InputString() {
This tells the compiler that you are implementing a function called InputString() of the class ShuntingYard. Otherwise it thinks you are trying to declare a separate function that is separate from ShuntingYard, and thus does not know about its private variables.

C++ error: "expected constructor, destructor, or type conversion before "(" token [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Having trouble at the start of this assignment. Im sure it is a very basic error, hopefully a fresh pair of eyes can help. I am getting the above code in my .cpp class file. I have attached the .cpp and the header. Error is in line 7 of the .cpp.
Any help would be appreciated.
#include "Encryptor.h"
Encryptor::Encryptor(){
}
Encryptor::Encryptor(key, plainText)
{
newKey = key;
newPlainText = plainText;
cout << newKey << "/t" << newPlainText << endl;
}
Encryptor::~Encryptor()
{
//dtor
}
/*string Encryptor::getEncryption(){
return encryptedFile
}*/
header:
#ifndef ENCRYPTOR_H
#define ENCRYPTOR_H
#include <iostream>
#include <string>
using std::string;
class Encryptor
{
public:
Encryptor();
Encryptor(string, string);
virtual ~Encryptor();
//Accessor Function
string getEncryption() const;
private:
string newKey;
string newPlainText;
};
#endif // ENCRYPTOR_H
Line 7 should be:
Encryptor::Encryptor(string key, string plainText)
As you need to include types for the arguments.
You're not specifying the types for this constructor's definition
Encryptor::Encryptor(string key, string plainText)
^^^^^^ ^^^^^^
{
newKey = key;
newPlainText = plainText;
cout << newKey << "/t" << newPlainText << endl;
}
Furthermore this is not defined but just declared (as far as its definition stays commented out)
string getEncryption() const;
(and even that commented out definition lacks the const qualifier)