main within class?

Was looking for supplementary video tutorials to understand recursion and this is one that I couldn't understand

1) void main() within a class?
how does that work? i tried looking thru the books i have and can't find related info

2) tried to compile the code but encountered a
error: expected unqualified-id
public class DecimalToBinary {
^


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  #include <string>
#include <iostream>

using std::string;

public class DecimalToBinary {

	public static void main(String[] args) {
		String binary = findBinary(233,"");
	}

public static String findBinary(int decimal, String result) {
	if (decimal == 0) {
		return result;
	}

	result = decimal % 2 + result;		// result = "01001". decimal = 14
	
	return findBinary(decimal / 2, result); 	// decimal = 14, result = ...
}


}
Where did you get that code from?

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

std::string decimalToBinary( unsigned n )
{
   return ( n < 2 ? "" : decimalToBinary( n / 2 ) ) + "01"[n % 2];
}

int main()
{
   for ( unsigned i = 0; i < 32; i++ ) std::cout << i << '\t' << decimalToBinary( i ) << '\n';
}
> void main() within a class?
You've been reading too much Java.
void main is nonstandard but most compilers support it. It was popular for a time in the late 90s, but it was never meant to be correct.

main can't be in a class in c++. It is the starting point of the program and there is no object at that point to hook it into. Java forces main to be in an object, because java wants to control how you code and prevent you from doing anything. (Pardon my bitterness but every time I am forced to use it, I spend 75% of my time trying to work around artificial limitations in the language).

Java came from c++ as an attempt to make a C++ like language that did not have the portability problems of C++ (which were a LOT worse when this was going on and are actually much better now in many ways). The shared syntax often means that java code and c++ code look very similar -- so much so that the inner parts of many functions are totally identical in both languages esp if doing math (strings are fairly different). I believe you have mistaken some java code for c++.
Last edited on
Thanks, now i realized what's wrong.

i was googling and searching in youtube for " C++ Recursion" to learn more about recursion.

and came across this youtube tutorial
https://www.youtube.com/watch?v=IJDJ0kBx2LM

and I failed to notice that the code used it's Java.
Topic archived. No new replies allowed.