Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'class' keyword in variable definition in C++

Tags:

Before anyone asks, yes, this is part of a homework, and yes, I did a lot of Googling before asking. I spent the last hour searching intensively on Google with many, many different keywords, but just could not find anything.

So here goes the question :

What does the following variable definition mean: class MyClass* myClass;?

I tried that code with something like class MyClass* myClass = new MyClass(); and found that it simply creates a pointer to a new instance of MyClass.

So, what's the advantage of using the class prefix? Does it make any difference?

Does someone have a link to some resources about it? I simply could not find anything (it's really, really hard to find things other than "class definition"!).

Thanks a lot!

like image 797
Über Lem Avatar asked Jan 18 '15 04:01

Über Lem


People also ask

Can we define class in C?

C ClassesA class consists of an instance type and a class object: An instance type is a struct containing variable members called instance variables and function members called instance methods. A variable of the instance type is called an instance.

What is keyword and variable in C?

A variable can have alphabets, digits, and underscore. A variable name can start with the alphabet, and underscore only. It can't start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, goto, etc.

What is keyword and variable?

Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive.

What is the class keyword in C++?

The class keyword is used to create a class called MyClass . The public keyword is an access specifier, which specifies that members (attributes and methods) of the class are accessible from outside the class.


2 Answers

An elaborated type specifier is a type name preceded by either the class, struct, enum, or union keyword.

class identifier 
struct identifier 
enum identifier 
union identifier

An elaborated type specifier is used either for emphasis, or to reveal a type name that is hidden by the declaration of a variable with the same name in the same scope.

source

like image 125
Felix D. Avatar answered Sep 25 '22 12:09

Felix D.


Actually it is optional to use class while creating object of class. In C language it is compulsory to use struct in front of struct name to create its variable. As C++ is superset of C. There is only one difference between struct and class in C++, and that is of access modifier.

To keep backward compatible it is permissible.

So,

class MyClass* myClass = new MyClass();

And,

MyClass* myClass = new MyClass();

Both are same.

like image 26
Pranit Kothari Avatar answered Sep 24 '22 12:09

Pranit Kothari