How are classes not objects in C++? - c++

I was reading "Design Patterns: Elements of Reusable Object-Oriented Software", (specifically the chapter about the prototype design pattern) and it stated that...
"Prototype is particularly useful with static languages like C++ where classes are not objects, and little or no type information is available at run-time." (pg 121)
(emphasis mine)
I had always thought that classes were synonymous to objects, and I'm confused as to what this statement means. How are classes not objects, and why does it matter if a language is static?

A class in C++ is not an object: a class is a description of how to build an object, and a reference to a type of an object.
Compare with a language like Python: in python, like in C++, you instantiate an object from a class. Unlike C++, the class you used is also an object: it usually has type type, and you can create new ones at runtime, manipulate them like any other object, or even create objects which are classes which themselves have different types.
You may be wondering why you'd want this, and usually you don't need it -- it's like C++ template meta-programming, you only need it when you need it because you can't achieve your goal in any other way. It's probably also the case that problems you'd solve in Python with meta-classes you'd solve in C++ using template meta-programming.

In C++, this declares a class:
class A {
public:
int a;
};
whereas this declares an object:
A a;
One cannot interrogate a class a run-time, as one can interrogate an object. It makes sense to say, "object 'a', what is your address? Please invoke operator+. etc." In C++, with its static typing, it makes no sense to say, "Class A, what is your list of members? Please add a new member, "b"."
In other languages (Python comes to mind), one can manipulate classes in this way, because each class is also an object. In addition to serving as a template for objects, the class itself is an object -- it can be printed, modified, etc.

For example, a class could describe what a book is: Name, Author, Date of Publishing, Description.
An object of the "Book" class would be a specific book: C++ Primer Plus, Stephen Prata, 2005, A book that teaches C++.
So, classes are not the same as objects.

To expand on what Andrew Aylett said.
A class in C++ is not an object: a class is a description of how to build an object, and a reference to a type of an object.
Furthermore, in languages like Python or smalltalk. Everything is an object. A function is a object, a class is a object. As such these languages are Dynamically Typed, meaning that types are checked during runtime and variables can take on any type.
C++ is statically typed. Variables can only take on one type, and type checking is performed at compile time.
So in python for instance, you can modify a class on the fly. Add functions and fields, because it is an object, and can be modified.

What that sentence refers is to is the fact that classes are not first-order entities in a language like C++. In other languages, you can pass a class as a parameter to a function, e.g., the same way as you can pass an object or a function as a parameter.
There are many more implications of being classes first-order entities or not, e.g., the possibility of modifying a class at runtime, or inspecting the full internals of a class, etc.
Usually classes are found to be first-order entities in dynamic languages like ruby, or in the meta object protocol for lisp, etc.
Hope this clarifies it a bit.

Classes are not the same as Objects. A class is (more or less) the type, and an Object is the instance, simmiliar to the following:
int i;
YourClass object;
Here you wouldn't say i and int are the same -- neither are YourClass and object.
What the statement wants to say: Many object orientated languages are very object orientated, so that they start making everything (or nearly everything) an object (of one or another class). So in many languages a class would be an instance (hence an object) of some class class (which can be confusing).
This sometimes has advantages, as you can treat classes (that's types) in such languages like you could treat any other object. You can than do very dynamic stuff with them, like store them in variables or even manipulate the classes during runtime (e.g. to create new classes your program finds the need to have).
Take a look at this c++-similiar pseudo code:
YourClass myObject = new YourClass(); // creates an object (an instance)
Class baseClass = myObject.get_class(); // store the class of myObject in baseClass. That's storing a type in a variable (more or less)
Class subClass = myObject.inherit(); // dynamically create a new class, that only exists in variable subClass (a Class-object), inheriting from baseClass
subClass.add_method(some_function); // extend the new class by adding a new method
subClass.get_class() subClass.create_instance(); // declare a new variable (object) of your newly created type
BaseClass another_onne = subClass.create_instance(); // also valid, since you inherited
This obviously doesn't translate well to c++, because of c++'s strict typing. Other languages are more dynamic in typing, and there this flexibility can come in handy (and make thinks more complicated; sometimes both at the same time). Still I think it explains the principle, if you understand c++.

I had always thought that classes were synonymous to objects
The language in OOP literature is sometimes not specific. It doesn't help either that programming languages have somewhat different notions of what an object is.
A class is a template or definition from where objects (instances of that class) are created. That is, a class provides the structure, type signatures and behaviors that objects of that class (or type... more on that later.)
An object is just a location in memory of an instance of that class.
Wikipedia provides good documentation on this. I suggest you read it:
http://en.wikipedia.org/wiki/Class_(computer_programming)
http://en.wikipedia.org/wiki/Object_(object-oriented_programming)
Also, there is the concept of a type. A type (or interface as sometimes called in some literature or programming languages) is typically the collection of type/method signatures (and possibly behavior). Things like Java interfaces and C++ pure virtual classes tend to represent types (but aren't exactly the same).
Then a class that conforms to that type (be it interface or pure virtual class) is an implementation of that type.
That class, that type implementation is just a recipe of how to construct objects of that class/type in memory.
When you instantiate a class/type, you reify, construct an instance (object) of that class in memory.
In C++, a class is not an object since a class itself is not instantiated. A C++ class is not an instance of some other class (see the definitions I put above.)
OTH, in languages like Java, a class itself is represented by instances of a primordial class (java.lang.Class). So a class X has an object in memory (an java.lang.Class instance) associated with it. And with it, with that "class" object, you can (in theory) instantiate or manufacture another instance (or object) of class/type X.
It can get confusing. I strongly suggest you search and read the literature on classes, types, prototypes and objects/instances.
and I'm confused as to what this statement means. How are classes not
objects,
As explained above. A class is not an object. An object is an instance, a piece of memory constructed and initialized by the "recipe" of a class or type.
and why does it matter if a language is static?
That part of the book is a bit misleading because Java, for example, is statically typed and yet, classes can be object themselves. Perhaps the text is refering to dynamically typed languages (like JavaScript) where classes can also be objects or instances.
My suggestion is to never use the word object, and to simply limit the vocabulary to "classes" and "instances". But that's my personal predilection. Other people might disagree, and so be it.

The simpler I can put it for you to understand it:
An object is a "physical" instance of a class. It consumes memory while the program is running.
A class describes an object: Hierarchy, properties, methods. A class it's like a "template" for creating objects.

When a class is said to be an object, it means that there's an object that represents that class at runtime. In C++, classes are dissolved at compile time. Their instances (i.e. objects) are merely sequences of bytes holding the object's fields, without any reference to the class itself. Now, C++ does provide some type information at runtime via RTTI, but that's only for polymorphic types, and is not considered a class object.
The lack of having objects that represent classes at runtime is the reason there's no reflection in C++ - there's just no way to get information about a certain class, as there's no object that represent it.
BTW, C++ is considered a 2-level language: objects are instances of classes, but classes are not instances of anything, because they only exist at compile type. On 3-level languages such as C# and Java, classes are also objects at runtime, and as such, are themselves instances of yet another class (Class in Java, Type in C#). The last class is an instance of itself, hence the language only has 3 levels. There are languages with more levels, but that's beyond the scope of this question...

Related

Is Abstract class an example of Abstract data type?

I'm getting confused by these two. What I learned is that Abstract data type is a mathematical model for data type, where it specifies the objects and the methods to manipulate these objects without specifying the details about the implementation of the objects and methods. Ex: an abstract stack model defines a stack with push and pop operations to insert and delete items to and from the stack. We can implement this in many ways, by using linked lists, arrays or classes.
Now, coming to the definition of abstract class, its a parent class which has one or more methods that doesn't have definition(implementation?) and cannot be instantiated (much like we can't implement an abstract stack as it is, without defining the stack's underlying mechanism through one of the concrete data structures). For ex: if we have an abstract class called Mammal which includes a function called eat(), we don't know how a mammal eats because a mammal is abstract. Although we can define eat() for a cow which is a derived class of mammal. Does this mean that mammal serves as an adt and cow class is an implementation of the mammal adt?
Correct me if I'm wrong in any way. Any kind of help would be really appreciated.
Abstract data type is a mathematical model for data type...
Now, coming to the definition of abstract class...
You need to distinguish between theoretical mathematical models and a practical implementation techniques.
Models are created by people in order to reason about problems easily, in some comprehensible, generalized way.
Meanwhile, the actual code is written in order to work and get the job done.
"Abstract data type" is a model. "Abstract class" is a programming technique which some programming languages (C++, C#, Java) support on the language level.
"Abstract data type" lets you think and talk about the solution of a problem, without overloading your brain with unnecessary (at this moment) implementation details. When you need a FIFO data structure, you say just "stack", but not "a doubly-linked list with the pointer to the head node and the ability to...".
"Abstract class" lets you write the code once and then reuse it later (because that is the point of OOP - code reuse). When you see that several types have a common interface and functionality - you may create "an abstract class" and put the intersection of their functionality in inside, while still being able to rely on yet unimplemented functions, which will be implemented by some concrete type later. This way, you write the code once and when you need to change it later - it's only one place to make the change in.
Note:
Although, in C++ ISO Standard (at least in the draft) there is a note:
Note: The abstract class mechanism supports the notion of a general concept,
such as a shape, of which only more concrete variants, such as circle
and square, can actually be used.
but it is just a note. The real definition is:
A class is abstract if it has at least one pure (aka unimplemented) virtual function.
which leads to the obvious constraint:
no objects of an abstract class can be created except as subobjects of
a class derived from it
Personally, I like that C++ (unlike C# and Java) doesn't have the keyword "abstract". It only has type inheritance and virtual functions (which may remain unimplemented). This helps you focus on a practical matter: inherit where needed, override where necessary.
In a nutshell, using OOP - be pragmatic.
The term "abstract data type" is not directly related to anything in C++. So abstract class is one of the potential implementation strategies to implement abstract data types in the given language. But there are a lot more techniques to do that.
So abstract base classes allow you to define a set of derived classes and give you the guarantee that all interfaces ( declarations ) have also an implementation, if not, the compiler throws an error, because you can't get an instance of your class because of the missing method definition.
But you also can use compile time polymorphism and related techniques like CRTP to have abstract data types.
So you have to decide which features you need and what price you want to pay for it. Runtime polymorphism comes with the extra cost of vtable and vtable dispatching but with the benefit of late binding. Compile time polymorphism comes with the benefit of much better optimizable code with faster execution and less code size. Both give you errors if an interface is not implemented, at minimum at the linker stage.
But abstract data types with polymorphism, independend of runtime or compile time, is not a 1:1 relation. Making things abstract can also be given by simply defining an interface which must be somewhere fulfilled.
In a short: Abstract data types is not a directly represented in c++ while abstract base class is a c++ technique.
Is Abstract class an example of Abstract data type?
Yes, but in C++, abstract classes have become an increasingly rare example of abstract data types, because generic programming is often a superior alternative.
Ex: an abstract stack model defines a stack with push and pop
operations to insert and delete items to and from the stack. We can
implement this in many ways, by using linked lists, arrays or classes.
The C++ std::stack class template more or less works like this. It has member functions push and pop, and it's implemented in terms of the Container type parameter, which defaults to std::deque.
For an implementation with a linked list, you'd type std::stack<int, std::list<int>>. However, arrays cannot be used to implement a stack, because a stack can grow and shrink, and arrays have a fixed size.
It's very important to understand that the std::stack has absolutely nothing to do with abstract classes or runtime polymorphism. There's not a single virtual function involved.
Now, coming to the definition of abstract class, its a parent class
which has one or more methods that doesn't have
definition(implementation?) and cannot be instantiated
Yes, that's precisely the definition of an abstract class in C++.
In theory, such a stack class could look like this:
template <class T>
class Stack
{
public:
virtual ~Stack() = 0;
virtual void push(T const& value) = 0;
virtual T pop() = 0;
};
In this example, the element type is still generic, but the implementation of the container is meant to be provided by a concrete derived class. Such container designs are idiomatic in other languages, but not in C++.
much like we can't implement an abstract stack as it is, without defining the stack's underlying mechanism through one of the concrete data structures
Yes, you couldn't use std::stack without providing a container type parameter (but that's impossible anyway, because there's the default std::deque parameter), and you cannot instantiate a Stack<int> my_stack; either.

C++ Class References

Coming from Delphi, I'm used to using class references (metaclasses) like this:
type
TClass = class of TForm;
var
x: TClass;
f: TForm;
begin
x := TForm;
f := x.Create();
f.ShowModal();
f.Free;
end;
Actually, every class X derived from TObject have a method called ClassType that returns a TClass that can be used to create instances of X.
Is there anything like that in C++?
Metaclasses do not exist in C++. Part of why is because metaclasses require virtual constructors and most-derived-to-base creation order, which are two things C++ does not have, but Delphi does.
However, in C++Builder specifically, there is limited support for Delphi metaclasses. The C++ compiler has a __classid() and __typeinfo() extension for retrieving a Delphi-compatible TMetaClass* pointer for any class derived from TObject. That pointer can be passed as-is to Delphi code (you can use Delphi .pas files in a C++Builder project).
The TApplication::CreateForm() method is implemented in Delphi and has a TMetaClass* parameter in C++ (despite its name, it can actually instantiate any class that derives from TComponent, if you do not mind the TApplication object being assigned as the Owner), for example:
TForm *f;
Application->CreateForm(__classid(TForm), &f);
f->ShowModal();
delete f;
Or you can write your own custom Delphi code if you need more control over the constructor call:
unit CreateAFormUnit;
interface
uses
Classes, Forms;
function CreateAForm(AClass: TFormClass; AOwner: TComponent): TForm;
implementation
function CreateAForm(AClass: TFormClass; AOwner: TComponent): TForm;
begin
Result := AClass.Create(AOwner);
end;
end.
#include "CreateAFormUnit.hpp"
TForm *f = CreateAForm(__classid(TForm), SomeOwner);
f->ShowModal();
delete f;
Apparently modern Delphi supports metaclasses in much the same way as original Smalltalk.
There is nothing like that in C++.
One main problem with emulating that feature in C++, having run-time dynamic assignment of values that represent type, and being able to create instances from such values, is that in C++ it's necessary to statically know the constructors of a type in order to instantiate.
Probably you can achieve much of the same high-level goal by using C++ static polymorphism, which includes function overloading and the template mechanism, instead of extreme runtime polymorphism with metaclasses.
However, one way to emulate the effect with C++, is to use cloneable exemplar-objects, and/or almost the same idea, polymorphic object factory objects. The former is quite unusual, the latter can be encountered now and then (mostly the difference is where the parameterization occurs: with the examplar-object it's that object's state, while with the object factory it's arguments to the creation function). Personally I would stay away from that, because C++ is designed for static typing, and this idea is about cajoling C++ into emulating a language with very different characteristics and programming style etc.
Type information does not exist at runtime with C++. (Except when enabling RTTI but it is still different than what you need)
A common idiom is to create a virtual clone() method that obviously clones the object which is usually in some prototypical state. It is similar to a constructor, but the concrete type is resolved at runtime.
class Object
{
public:
virtual Object* clone() const = 0;
};
If you don't mind spending some time examining foreign sources, you can take a look at how a project does it: https://github.com/rheit/zdoom/blob/master/src/dobjtype.h (note: this is a quite big and evolving source port of Doom, so be advised even just reading will take quite some time). Look at PClass and related types. I don't know what is done here exactly, but from my limited knowledge they construct a structure with necessary metatable for each class and use some preprocessor magic in form of defines for readability (or something else). Their approach allows seamlessly create usual C++ classes, but adds support for PClass::FindClass("SomeClass") to get the class reference and use that as needed, for example to create an instance of the class. It also can check inheritance, create new classes on the fly and replace classes by others, i. e. you can replace CDoesntWorksUnderWinXP by CWorksEverywhere (as an example, they use it differently of course). I had a quick research back then, their approach isn't exceptional, it was explained on some sites but since I had only so much interest I don't remember details.

Abstract Factory and classes as first class objects

A theoretical question. I'm reading Gof's Design Patterns, section Abstract Factory. The book mentions the possibility of implementing this pattern like a Prototype or, if the language permits it, with a Prototype which stores classes instead of objects.
I have understood this; e.g. in Java or Smalltalk, classes are also objects (in Java they are in fact instances of the class Class). Hence, we can store them inside a class and, when needed, invoke the creation of instances of these classes.
In C++, classes are not first class objects; hence, we shouldn't be able to follow this approach. However, couldn't we declare nested classes inside inside a Concrete Factory, with methods which invoke their constructors (and return their instances)? The final result would be the same of other languages such as Java or Smalltalk. Am I right?
Thank you for your attention.

Objects vs instance in python

In C++ there are just objects and classes, where objects are instances of classes.
In Python, a class definition (i.e., the body of a class) is called an object.
And, the object in C++ is called instance in python.
Check this
Am I wrong?
EDIT : Actually can someone explain with example difference of object vs instance
EDIT : In python, everything will inherit from object class & hence everything is an object (i.e object of object class).
A Class is also an object (i.e object of object class).
Instance is the name used to call the object of any class.(a.k.a c++ object).
Please refer this
In Python, a class definition (i.e., the body of a class) is called an object
Actually, this is still called a class in Python. That's why you define it like this:
class Foo(object):
pass
The class keyword is used because the result is still called a class.
The word object is in parentheses to show that Foo is derived from the class called object. Don't be confused -- any existing class could be used here; more than one, in fact.
The reason you usually derive classes from object is a historical accident but probably is worth a detail. Python's original object implementation treated user-defined classes and built-in types as slightly different kinds of things. Then the language's designer decided to unify these two concepts. As a result, classes derived from object (or from a descendant of object) behave slightly differently from classes that are not derived from object and are called new-style classes. Old-style classes, on the other hand, were ones defined like this:
class Foo:
pass
class Bar(Foo):
pass
Note these do not inherit from object or from anything else that inherits from object. This makes them old-style classes.
When working with Python 2.x, your classes should almost always inherit from object, as the new-style objects are nicer to work with in several small but important ways.
To further confuse things, in Python 3.0 and later, there are no old-style classes, so you don't have to derive from object explicitly. In other words, all the above classes would be new-style classes in Python 3.x.
Now, back to the matter at hand. Classes are objects because everything is an object in Python. Lists, dictionaries, integers, strings, tuples... all of these are objects, and so are the building blocks of Python programs: modules, functions, and classes. You can create a class using the class keyword and then pass it to a function, modify it, etc. (For completeness, you can also create a class using the type() function.)
A class is a template for building objects, which are referred to as instances. This part you already know. You instantiate objects similar to calling a function, passing in the initial values and other parameters:
mylist = list("abc") # constructs ["a", "b", "c"]
Behind the scenes, this creates an instance, then calls the new instance's __init__() method to initialize it. Since everything's an object in Python, instances of a class are also objects.
One last thing you might want to know is that just as classes are templates for building objects, so it is possible to have templates for building classes. These are called metaclasses. The base metaclass is called type (that is, an ordinary new-style class is an instance of type).
(Yes, this is the same type that I mentioned earlier can be used to create classes, and the reason you can call it to create classes is that it's a metaclass.)
To create your own metaclass, you derive it from type like so:
class mymeta(type):
pass
Metaclasses are a fairly advanced Python topic, so I won't go into what you might use them for or how to do it, but they should make it clear how far Python takes the "everything's an object" concept.
Terminology-wise, classes and instances are both called objects in Python, but for you as a regular Python programmer this is of no importance. You can see Python's classes and instances pretty much as C++'s classes and instances:
class MyClass:
data = 1
mc = MyClass()
MyClass is a class and mc is an instance of class MyClass.
Python is much more dynamic in nature than C++ though, so its classes are also objects. But this isn't something programmers usually are exposed to, so you can just not worry about it.
Everything in Python is an object. Even classes, which are instances of metaclasses.
Since you asked for "english please", I'll try to make it simple at the cost of detail.
Let's ignore classes and instances at first, and just look at objects.
A Python object contains data and functions, just like objects in every other object oriented programming language. Functions attached to objects are called methods.
x = "hello" #now x is an object that contains the letters in "hello" as data
print x.size() #but x also has methods, for example size()
print "hello".size() #In python, unlike C++, everything is an object, so a string literal has methods.
print (5).bit_length() #as do integers (bit_length only works in 2.7+ and 3.1+, though)
A class is a description (or a recipe, if you will) of how to construct new objects. Objects constructed according to a class description are said to belong to that class. A fancy name for belonging to a class is to be an instance of that class.
Now, earlier I wrote that in Python everything is an object. Well, that holds for stuff like functions and classes as well. So a description of how to make new objects is itself an object.
class C: #C is a class and an object
a = 1
x1 = C() #x1 is now an instance of C
print x1.a #and x1 will contain an object a
y = C #Since C is itself an object, it is perfectly ok to assign it to y, note the lack of ()
x2 = y() #and now we can make instances of C, using y instead.
print x2.a #x2 will also contain an object a
print C #since classes are objects, you can print them
print y #y is the same as C.
print y == C #really the same.
print y is C #exactly the same.
This means that you can treat classes (and functions) like everything else and, for example, send them as arguments to a function, which can use them to construct new objects of a class it never knew existed.
In a very real sense, everything in Python is an object: a class (or any
type) is an object, a function is an object, a number is an object...
And every object has a type. A "type" is a particular type of object (a
class, if you wish), with additional data describing the various
attributes of the type (functions, etc.). If you're used to C++, you
can think of it as something like:
struct Type;
struct Object // The base class of everything.
{
Type* myType;
// Some additional stuff, support for reference counting, etc.
};
struct Type : Object
{
// Lots of additional stuff defining type attributes...
};
When you define a new class in Python, you're really just creating a new
instance of Type; when you instantiate that class, Python initializes
the myType member with a pointer to the correct instance of Type.
Note, however, that everything is dynamic. When you define a type
Toto (by executing a class definition—even defining a type is a
runtime thing, not compile time, as in C++), the Python interpreter
creates an instance of Type, and puts it in a dictionary
(map<string, Object*>, in C++ parlance) somewhere. When the interpreter
encounters a statement like:
x = Toto()
, it looks up Toto in the dictionary: if the Object referred to has
the type Type, it constructs a new instance of that object, if it has
type Function (functions are also objects), it calls the function.
(More generally, a type/class may be callable or not; if the type of the
Object found in the dictionary under Toto is callable, the Python
interpreter does whatever the object has defined "call" to mean. Sort
of like overloading operator()() in C++. The overload of
operator()() for Type is to construct a new object of that type.)
And yes, if you come from a classical background—strictly procedural,
structured, fully-compiled languages, it can be pretty confusing at
first.

Treating classes as first-class objects

I was reading the GoF book and in the beginning of the prototype section I read this:
This benefit applies primarily to
languages like C++ that don't treat
classes as first class objects.
I've never used C++ but I do have a pretty good understanding of OO programming, yet, this doesn't really make any sense to me. Can anyone out there elaborate on this (I have used\use: C, Python, Java, SQL if that helps.)
For a class to be a first class object, the language needs to support doing things like allowing functions to take classes (not instances) as parameters, be able to hold classes in containers, and be able to return classes from functions.
For an example of a language with first class classes, consider Java. Any object is an instance of its class. That class is itself an instance of java.lang.Class.
For everybody else, heres the full quote:
"Reduced subclassing. Factory Method
(107) often produces a hierarchy of
Creator classes that parallels the
product class hierarchy. The Prototype
pattern lets you clone a prototype
instead of asking a factory method to
make a new object. Hence you don't
need a Creator class hierarchy at all.
This benefit applies primarily to
languages like C++ that don't treat
classes as first-class objects.
Languages that do, like Smalltalk and
Objective C, derive less benefit,
since you can always use a class
object as a creator. Class objects
already act like prototypes in these
languages." - GoF, page 120.
As Steve puts it,
I found it subtle in so much as one
might have understood it as implying
that /instances/ of classes are not
treated a first class objects in C++.
If the same words used by GoF appeared
in a less formal setting, they may
well have intended /instances/ rather
than classes. The distinction may not
seem subtle to /you/. /I/, however,
did have to give it some thought.
I do believe the distinction is
important. If I'm not mistaken, there
is no requirement than a compiled C++
program preserve any artifact by which
the class from which an object is
created could be reconstructed. IOW,
to use Java terminology, there is no
/Class/ object.
In Java, every class is an object in and of itself, derived from java.lang.Class, that lets you access information about that class, its methods etc. from within the program. C++ isn't like that; classes (as opposed to objects thereof) aren't really accessible at runtime. There's a facility called RTTI (Run-time Type Information) that lets you do some things along those lines, but it's pretty limited and I believe has performance costs.
You've used python, which is a language with first-class classes. You can pass a class to a function, store it in a list, etc. In the example below, the function new_instance() returns a new instance of the class it is passed.
class Klass1:
pass
class Klass2:
pass
def new_instance(k):
return k()
instance_k1 = new_instance(Klass1)
instance_k2 = new_instance(Klass2)
print type(instance_k1), instance_k1.__class__
print type(instance_k2), instance_k2.__class__
C# and Java programs can be aware of their own classes because both .NET and Java runtimes provide reflection, which, in general, lets a program have information about its own structure (in both .NET and Java, this structure happens to be in terms of classes).
There's no way you can afford reflection without relying upon a runtime environment, because a program cannot be self-aware by itself*. But if the execution of your program is managed by a runtime, then the program can have information about itself from the runtime. Since C++ is compiled to native, unmanaged code, there's no way you can afford reflection in C++**.
...
* Well, there's no reason why a program couldn't read its own machine code and "try to make conclusions" about itself. But I think that's something nobody would like to do.
** Not strictly accurate. Using horrible macro-based hacks, you can achieve something similar to reflection as long as your class hierarchy has a single root. MFC is an example of this.
Template metaprogramming has offered C++ more ways to play with classes, but to be honest I don't think the current system allows the full range of operations people may want to do (mainly, there is no standard way to discover all the methods available to a class or object). That's not an oversight, it is by design.