How can we initialize a string argument in the C++ function prototype? I want to assign a default value for a string argument in my function
int test(string& s="rom");
int test(string& s) {
return s.size();
}
int main(int argc, char *argv[]) {
cout << test() << endl;
return 0;
}
You can use this:
void func(const std::string& argument = "default") { ... }
you can also do:
void func(std::string argument = "default") { ... }
but that really depends on if you need that copy inside the function.
Like this:
void func(int a, string str="default-string")
{
cout << a << str << endl;
}
And call like this:
int main(void)
{
func(3); // use default string
func(3, "new-string"); // use new string
return 0;
}
Related
i have these set and get methods declared in my main cpp file
void issuesofRelevance::setApproach(int Approach) {
approach = Approach;
}
int issuesofRelevance::getApproach() {
return approach;
}
void issuesofRelevance::setSignifiance(int Significance) {
significance = Significance;
}
int issuesofRelevance::getSignificance() {
return significance;
}
The following H file is attatched in which I call the setMethods in its constructor.
class issuesofRelevance
{
public:
std::vector<std::string> issueName;
int significance;
int approach;
std::vector<std::string> newList;
issuesofRelevance(std::vector<std::string> issueName, int significance, int approach){
issueName = issueName;
significance = significance;
approach = approach;
setApproach(15);
setSignifiance(15);
}
issuesofRelevance();
void setIssues();
std::string getIssues();
void setApproach(int x);
void setSignifiance(int);
int getApproach();
int getSignificance();
};
I call the get functions in main int() as such
cout << object.getApproach();
cout << object.getSignificance();
However, when i go to run the code in the console I get no output when it should return the values of 10 and 15. Im unsure as to why this is occuring
Thankyou.
my full main as requested
int main(int argc, char* argv[]) { //takes in n, number of electorates, and m, the number of campagian days
issuesofRelevance newIssues(newIssues.issueName, newIssues.significance, newIssues.approach);
return 0;
Party party;
Person person;
Electrorates electorate;
string numberofElectoratesAsString = argv[1]; //number of electorates taking as a argument
string DaysOfElectionAsString = argv[2]; //takes in argument 2
int numberofElectorates = std::stoi(numberofElectoratesAsString);
int DaysOfElection = std::stoi(DaysOfElectionAsString );
cout << "Number of electorates: " << electorate.assignID(electorate.numberofElectorates(numberofElectorates));
cout << "Stance: " << person.setinitalStance(numberofElectorates, DaysOfElection) << endl;
newIssues.setIssues();
cout<<newIssues.getApproach()<< " "<<newIssues.getSignificance();
return 0;
}
default constructor
issuesofRelevance::issuesofRelevance(){
}
I have class Pstring
class Pstring
{
private:
string palindrome;
public:
Pstring() { palindrome = ""; }
Pstring(string pal) { setString(pal); }
void setString(string pal) { palindrome = pal; }
string getPal() const { return palindrome; }
};
an object in my main method Pstring palindrome(palin) defined by
string palin = "";
cout << "Enter a palindrome:\n";
getline(cin, palin);
Pstring palindrome(palin);
and a current test method bool isPalindrome(string pal)defined as
bool isPalindrome(string pal)
{
bool flag;
cout << "Do I have access to this?";
cout << pal;
//code goes here to check for palindrome, return bool
}
I want to have my Pstring class object palindrome use the method isPalindrome in main, but when I try and invoke the method by using palindrome.isPalinedrome(palin); it doesn't seem to have access to the method.
What can I do to allow a method outside the class to be used by a class object in main?
You don't have a isPalinedrome() method defined in the Pstring class, so you can't call it as palindrome.isPalinedrome() in your main code.
Instead of having Pstring try to call a function in your main code, you should move the palindrome logic into Pstring, and then the main code can ask Pstring when needed.
Try this:
class Pstring
{
private:
string value;
public:
Pstring() { }
Pstring(const string &s) { setString(s); }
void setString(const string &s) { value = s; }
string getString() const { return value; }
// add this...
bool isPalindrome() const {
//code goes here to check value for palindrome, return bool
}
};
Then your main code can do this:
bool isPalindrome(const string &value)
{
Pstring palindrome(value);
return palindrome.isPalindrome();
// or simply:
// return Pstring(value).isPalindrome();
}
int main()
{
string palin;
cout << "Enter a palindrome:\n";
getline(cin, palin);
if (isPalindrome(palin)) {
// do something ...
} else {
// do something else...
}
return 0;
}
Or this:
int main()
{
string palin;
cout << "Enter a palindrome:\n";
getline(cin, palin);
Pstring palindrome(palin);
if (palindrome.isPalindrome()) {
// do something ...
} else {
// do something else...
}
return 0;
}
You should add your test method into the class:
class Pstring
{
private:
string palindrome;
public:
// you don't need to initialize palindrome = "" (it's initialized by default)
Pstring() {}
// always pass strings as const reference unless you have
// special reason to do it another way...
Pstring(const string& pal) { setString(pal); }
void setString(const string& pal) { palindrome = pal; }
string getPal() const { return palindrome; }
bool isPalindrome() const // you don't have to pass string
{
bool flag;
cout << "Do I have access to this?";
cout << palindrome; // please note this
//code goes here to check for palindrome, return bool
}
};
And also please note the typo:
palindrome.isPalinedrome(palin);
You can use function pointer to implement it:
declare class:
class Pstring{
private:
string palindrome;
public:
Pstring() { palindrome = ""; }
Pstring(string pal) { setString(pal); }
void setString(string pal) { palindrome = pal; }
string getPal() const { return palindrome; }
//add a function pointer member:
bool(*isPalindrome) (string);
};
then define function:
bool isPalindrome(string pal)
{
bool flag;
cout << "Do I have access to this?";
cout << pal;
//code goes here to check for palindrome, return bool
return true;
}
now you can write code in main function:
string palin = "";
cout << "Enter a palindrome:\n";
getline(cin, palin);
Pstring palindrome(palin);
palindrome.isPalindrome = isPalindrome;//bind function
you can use the function by the object now:
palindrome.isPalindrome(palin);
Sorry. what's the point to create this class? the only thing you need is the helper function isPalindrome(const std::string&). If you need some kinda scope protection, put it into a namespace may look better
Sorry but I have to say you are just make things complicated.
C++ is not java. If you don't use it, you should not pay for it.
I've just found something as get the name of current function or get name of the caller, some variants to get or call the name as string.
What I want is to get the name of the function that I passed in arguments. Like this:
void Bar()
{
//do something
}
void Foo(void (*f)())
{
//this will output: Foo
std::cout << __FUNCTION__ << std::endl;
//How do I get the name passed to f? (in this case: Bar)
}
int main()
{
Foo(Bar);
return 0;
}
Thanks.
Edit: Here is an extremely near code for what I'm trying following the suggestion of #Jose.
thread_local const char * m_last_function_called = "";
#define register_function() {m_last_function_called = __FUNCTION__;}
inline const char * get_last_function() { return m_last_function_called; }
// const char * g_last_function_called = "";
// #define register_function() { g_last_function_called = __FUNCTION__; }
// inline const char * get_last_function() { return g_last_function_called; }
void print_last_func()
{
static std::mutex sync_cout;
std::lock_guard<std::mutex> l(sync_cout);
std::cout << get_last_function() << std::endl;
}
bool interruptFooTimer = false;
int FooTimer()
{
register_function();
print_last_func();
std::cout << "FooTimer.start" << std::endl;
int t = 0;
while(t<10)
{
if(interruptFooTimer==false)
{
sleep(1);
t++;
std::cout << "\tt=" << t << std::endl;
}
else
{
return -1;
}
}
std::cout << "FooTimer.end" << std::endl;
return 0;
}
void CallTrd(int (*f)())
{
std::thread TrdTemp(f);
TrdTemp.detach();
TrdTemp.~thread();
print_last_func();
}
int main()
{
CallTrd(FooTimer);
print_last_func();
int c = 0;
while(c<15)
{
if(c==7) {interruptFooTimer=true;}
sleep(1);
c++;
std::cout << "c=" << c << std::endl;
print_last_func();
}
return 0;
}
Observe that I call print_last_func() in different moments and all get the same value that was initialized in the variable. This sample code calls a thread without using join() because I can't wait for the thread to finish and also implement the detach() and ~thread to finish my program without any exception. The interruptFooTimer I'm using to safely "terminate" my thread.
What am I missing to get global the value acquired in register_function??
You cannot. __FUNCTION__ is expanded by compiler during the compilation time. You cannot get this information in runtime.
Use a helper macro:
#define Foo(x) FooHelper(#x, x)
void FooHelper(const char *f_name, void (*f)())
{
cout << f_name;
}
As others have already noted, you cannot do this directly.
First of all I would use std::function instead of a raw function pointer and std::string to hold the function's name.
I would also wrap these up like this:
template<class T>
struct Functor
{
std::function<T> functor_;
std::string name_;
Functor(const std::function<T>& functor, const std::string& name)
: functor_(functor)
, name_(name)
{}
};
You can then use it like so:
void Bar()
{
// do something
}
void Foo(const Functor<void()>& functor)
{
}
int main()
{
Functor<void()> f(std::bind(Bar), "Bar");
Foo(f);
return 0;
}
You can also use a macro to make things easier for you.
#define FUNCTOR(t, x, ...) Functor<t>(std::bind(&x, __VA_ARGS__), #x)
Which can be used like this:
int main()
{
auto f = FUNCTOR(void(), Bar);
return 0;
}
Note that if you take this approach that the function name might not be the same as what using __FUNCTION__ yields.
I don't know why you wanna do it, but I hope it's for debugging purpose. Obviously the easiest path is to pass the __FUNCTION__ as an argument as pointed out. But in my point of view, there's a better approach.
You could have for example, a global variable:
thread_local const char * g_last_function_called = "";
#define register_function() { g_last_function_called = __FUNCTION__; }
inline const char * get_last_function() { return g_last_function_called; }
void Bar()
{
register_function()
}
void Foo(void (*f)())
{
std::cout << get_last_function() << std::endl;
}
void my_func_that_doesnt_accept_nulls(CClass * p)
{
if (p == nullptr)
{
std::cout << " function" << get_last_function();
std::cout << "passed a bad pointer, fix it" << std::endl;
return;
}
}
Of course, this will not give you the right result in multi-thread, but you can probably fix that using a thread_local const char * g_last_function_called = "" variable.
The reason why I like this method is because all you have to do to remove it from your project is just a simple "find and replace" of register_function(), and since it uses plain pointers, there's no way it can slow your program at all.
Edit: this is how I'm testing the code
void print_last_func()
{
static std::mutex sync_cout;
std::lock_guard<std::mutex> l(sync_cout);
std::cout << get_last_function() << std::endl;
}
void HelloWorld1()
{
register_function();
print_last_func();
}
void HelloWorld2()
{
register_function();
print_last_func();
}
int main()
{
register_function();
std::thread t1(HelloWorld1);
std::thread t2(HelloWorld2);
print_last_func();
t1.join();
t2.join();
return 0;
}
I get: HelloWorld1, HelloWorld2, and main
So I'm trying to implement function parameters which can be uninitialized. Here is the code which I have written. My question is if it's legal by the ISO C++ standard (version 14 if possible).
#include <iostream>
#include <typeinfo>
using namespace std;
template<typename type>
struct nzeroinittmpliteral
{
nzeroinittmpliteral() { }
nzeroinittmpliteral(type arg) { d = arg; }
//nzeroinittmpliteral(const nzeroinittmpliteral &) = delete;
operator type () & { return d; }
operator type () && { return d; }
type d;
} ;
void func(bool bIsPointerValid, nzeroinittmpliteral<int *> pVar = {})
{
if(bIsPointerValid)
{
cout << *pVar << endl;
}
else
{
pVar = new int;
*pVar = 8;
cout << *pVar << endl;
delete pVar;
}
}
int main()
{
func(true, { (int *)&(const int &)int{9} } );
func(false);
}
If you want to pass a parameter that may be uninitialized, simply don't pass it, use overloading. Look:
void func(int value)
{
cout << value << endl;
}
void func()
{
// no 'value' was initialized here :)
func(8);
}
Or simply give a default value to the parameter if you will provide one anyway in your body:
void func(int value = 8)
{
cout << value << endl;
}
Besides that, you can take a look at boost::optional:
void func(boost::optional<int> optvalue = boost::none) {
if (optvalue) {
cout << *optvalue << endl;
} else {
// nothing passed
cout << "foo" << endl;
}
}
Directly answering your question: your code is valid.
func(true, { (int *)&(const int &)int{9} } );
By casting the temporary to a const reference, you extend its lifetime to the lifetime of the reference itself, which ends after func returns. But this is too redundant, you could simply have written:
void func(int* value) { if (value) {...} }
func(&(const int &)9);
func(nullptr);
The actual parameter being passed is your nzeroinittmpliteral and it is initialized by calling one of the constructors, always. The default constructor doesn't initialize the d member, but this is no big improvement as it is just a pointer. Using nullptr is better and removes the need for the bool parameter.
I have this C++ class:
class Test
{
private:
string _string;
public:
Test()
{
}
Test(const char *s)
{
Test((string)s);
}
Test(string s)
{
_string = s;
}
operator const char *()
{
return _string.c_str();
}
operator string()
{
return _string;
}
};
If I use this code in main "1234" is printed to the console:
int main()
{
Test test = string("1234");
string s = test;
cout << s << endl;
return 0;
}
But with this, nothing is printed:
int main()
{
Test test = "1234"; // Only change
string s = test;
cout << s << endl;
return 0;
}
The only difference is which constructor is called. It apperas that the _string variable is a default string instance with the value "" but I don't see how that could have happend. I thought that since _string is on the stack, the assignment I do is safe.
This
Test(const char *s)
{
Test((string)s);
}
does not chain the constructors. It just creates a temporary object in the body of the function. What you need is:
Test(const char *s) : Test(string(s))
{
}