Confused about literal and class method


In Javascript you can get substring "string".method(x,y);

how come I get this in C++ by passing a literal but not an object?

in C i do this

class s {

private:
char[2];
public:
int subs(char[]);
};

int s::subs(char ch[]){
//loop
//i++;
return i;//as substring length
}
easiest/laziest way would be to initialise a std::string passing in your string literal to the constructor then just call size() on that. wrap it in a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

size_t GetLength(const char array[])
{
	std::string fooString(array);
	return fooString.size();
}

int main()
{
	std::cout << "Length: " << GetLength("Foo") << std::endl;
	return 0;
}
Last edited on
How? when I initialise I must initialise a var, but I want to pass a literal as JS

"Hello".len(); //in c++
I updated post with an example.

I don't see the point of this:

 
"Hello".len();


it's a literal so you know the length at compile time?
Why not just use 5 in it's place?
Just want to know if its possible in c/c++, because I want to know the technique how you compute something without making an object for it
Last edited on
I am guessing, its the job of compiler to do something like this...
Just want to know if its possible in c/c++
No.
You can call methods on string literals using C++14: http://coliru.stacked-crooked.com/a/6b6a2e5266cff783

I stand corrected :)
So its implemented by compiler correct? :)
And c++14 is not standard yet, correct?
Ib both javascript and c++ this will create an object and immideatly destroy it. In C++ this should be remembered if you want to get pointer/reference to object/its internals.

If you want to avoid runtime expenses, you should look into constexpr functions which works neatly with string literals.
Last edited on
got it now


Year C++ Standard Informal name
1998 ISO/IEC 14882:1998[12] C++98
2003 ISO/IEC 14882:2003[13] C++03
2007 ISO/IEC TR 19768:2007[14] C++TR1
2011 ISO/IEC 14882:2011[4] C++11
2014 N3690 (working draft C++14)[15] C++14
2017 to be determined C++17
wiki
Ib both javascript and c++ this will create an object and immideatly destroy it.

This is NOT programmers job, but compilers?
Last edited on
C++14 was standartised in August. It is already 5 month standard.
Yes. it is a syntax sugar. s at the end of string literal converts it to the std::string
Last edited on
Thanks everyone
Topic archived. No new replies allowed.