Cpp Tutorial: Different types of Classes in C++

In this chapter we shall look at different types of classes available in C++
1. Global Classes in C++
2. Local Classes in C++
3. Nested Classes in C++
4. Anonymous classes in C++

1. Global Classes in C++

1. Class defined outside of all the functions is called as Global Class.
2. The objects can be created anywhere in the program.
Example:
#include <iostream>
using namespace std;

class MyClass
{
    public:

    void display();
};

void MyClass::display()
{
    cout<<"In display function"<<endl;
}

int main(void)
{
    MyClass obj;
    obj.display();
}
Output:
In display function

2. Local Classes in C++

1. Classes created inside a function is called as local classes.
2. The object can be created inside of that function.
3. Lifetime is till the execution of the function.
4. Static data members should not be present.
5. Static member functions can be present.
Example:
#include <iostream>
using namespace std;

int main(void)
{
    
    class MyClass
    {
        public:
    
        void display()
        {
            cout<<"In display function"<<endl;
        }
        
    };

    MyClass obj;
    obj.display();
}
Output:
In display function

3. Nested Classes in C++

1. Classes inside a class is called as nested class.
Example:
#include <iostream>
using namespace std;

class MyClass
{
    public:

    void outer_display()
    {
        cout<<"In display function from outer class"<<endl;
    }
    
    class MyClassInner
    {
        public:
    
        void inner_display()
        {
            cout<<"In display function from inner class"<<endl;
        }
        
    };
    
};

int main(void)
{
    MyClass obj;
    obj.outer_display();
    
    MyClass :: MyClassInner inner_obj;
    inner_obj.inner_display();

}
Output:
In display function from outer class
In display function from inner class

4. Anonymous classes in C++

1. Classes with no name are called as Anonymous classes.
2. These classes cannot have constructor or destructors.
3. Anonymous class cannot sent arguments to functions.
4. They also cannot be used as return values from functions.
#include <iostream>
using namespace std;

class
{
    public:

    void display()
    {
        cout<<"In display function"<<endl;
    }

}obj;

int main(void)
{
    obj.display();

}

Output:

In display function
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *