The Wayback Machine - https://web.archive.org/web/20240826183116/https://www.geeksforgeeks.org/structure-vs-class-in-cpp/
Open In App

Difference Between Structure and Class in C++

Last Updated : 22 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, a structure works the same way as a class, except for just two small differences. The most important of them is hiding implementation details. A structure will by default not hide its implementation details from whoever uses it in code, while a class by default hides all its implementation details and will therefore by default prevent the programmer from accessing them. The following table summarizes all of the fundamental differences.

Class

Structure

1. Members of a class are private by default. 1. Members of a structure are public by default. 
2. An instance of a class is called an ‘object’. 2. An instance of structure is called the ‘structure variable’.
3. Member classes/structures of a class are private by default but not all programming languages have this default behavior eg Java etc. 3. Member classes/structures of a structure are public by default.
4. It is declared using the class keyword. 4. It is declared using the struct keyword.
5. It is normally used for data abstraction and further inheritance. 5. It is normally used for the grouping of data
6. NULL values are possible in Class. 6. NULL values are not possible.

7. Syntax:

 class class_name{

         data_member;

         member_function;

  };

7. Syntax:

   struct structure_name{

         type structure_member1;

         type structure_member2;

   };

Some examples that elaborate on these differences:

1) Members of a class are private by default and members of a structure are public by default. 

For example, program 1 fails in compilation but program 2 works fine, 

Program 1:

C++




// C++ Program to demonstrate that
// Members of a class are private
// by default
#include <iostream>
 
using namespace std;
 
class Test {
    // x is private
    int x;
};
 
int main()
{
    Test t;
    // compiler error because x
    // is private
    t.x = 20;
 
    return t.x;
}


Time Complexity: O(1)
Auxiliary Space: O(1)

 
 Output:

./cf03c8d1-d4a3-43ea-a058-fe5b5303167b.cpp: In function 'int main()':
./cf03c8d1-d4a3-43ea-a058-fe5b5303167b.cpp:10:9: error: 'int Test::x' is private
     int x;
         ^
./cf03c8d1-d4a3-43ea-a058-fe5b5303167b.cpp:18:7: error: within this context
     t.x = 20;
       ^
./cf03c8d1-d4a3-43ea-a058-fe5b5303167b.cpp:10:9: error: 'int Test::x' is private
     int x;
         ^
./cf03c8d1-d4a3-43ea-a058-fe5b5303167b.cpp:20:14: error: within this context
     return t.x;
              ^

Program 2: 

C++




// C++ Program to demonstrate that
// members of a structure are public
// by default
#include <iostream>
 
using namespace std;
 
struct Test {
    // x is public
    int x;
};
 
int main()
{
    Test t;
    t.x = 20;
 
    // works fine because x is public
    cout << t.x;
}


Output

20

Time Complexity: O(1)
Auxiliary Space: O(1)

2) A class is declared using the class keyword, and a structure is declared using the struct keyword.

Syntax: 

class ClassName {
private:
    member1;
    member2;

public:
    member3;
    .
    .
    memberN;
};

Syntax: 

struct StructureName {
    member1;
    member2;
    .
    .
    .
    memberN;
};

3) Inheritance is possible with classes, and with structures

For example, programs 3 and 4 work fine.

Program 3:

C++




// C++ Program to demonstrate
// Inheritance with classes.
#include <iostream>
 
using namespace std;
 
// Base class
class Parent {
public:
    int x;
};
 
// Subclass inheriting from
// base class (Parent).
class Child : public Parent {
public:
    int y;
};
 
int main()
{
    Child obj1;
 
    // An object of class Child has
    // all data members and member
    // functions of class Parent.
    obj1.y = 7;
    obj1.x = 91;
    cout << obj1.y << endl;
    cout << obj1.x << endl;
 
    return 0;
}


Output

7
91

Time Complexity: O(1)
Auxiliary Space: O(1)

Program 4:

C++




// C++ Program to demonstrate
// Inheritance with structures.
#include <iostream>
 
using namespace std;
 
struct Base {
public:
    int x;
};
 
// is equivalent to
// struct Derived : public Base {}
struct Derived : Base {
public:
    int y;
};
 
int main()
{
    Derived d;
 
    // Works fine because inheritance
    // is public.
    d.x = 20;
    cout << d.x;
    cin.get();
    return 0;
}


 
Output

20

Time Complexity: O(1)
Auxiliary Space: O(1)

To know about the Difference between C structures and C++ structures refer to this article.



Previous Article
Next Article

Similar Reads

Difference between Single Bus Structure and Double Bus Structure
1. Single Bus Structure: In a single bus structure, one common bus is used to communicate between peripherals and microprocessors. It has disadvantages due to the use of one common bus. 2. Double Bus Structure: In a double bus structure, one bus is used to fetch instructions while other is used to fetch data, required for execution. It is to overco
2 min read
Android Studio Project Structure VS Eclipse Project Structure
Eclipse is a standard package that is ideal for java and plug-in development, as well as introducing new plugins. Eclipse is mostly used for Java because it is basically developed in Java. One of the reasons Eclipse is well-known for its Java IDE is because of this. To personalize the environment, Eclipse includes its own workspace and a flexible p
4 min read
Difference between Abstract Class and Concrete Class in Java
Abstract Class: An abstract class is a type of class in Java that is declared by the abstract keyword. An abstract class cannot be instantiated directly, i.e. the object of such class cannot be created directly using the new keyword. An abstract class can be instantiated either by a concrete subclass or by defining all the abstract method along wit
5 min read
Difference between Base class and Derived class in C++
Base Class: A base class is a class in Object-Oriented Programming language, from which other classes are derived. The class which inherits the base class has all members of a base class as well as can also have some additional properties. The Base class members and member functions are inherited to Object of the derived class. A base class is also
2 min read
Difference between Structure chart and Flow chart
1. Structure Chart : Structure Chart represents the hierarchical structure of modules. It represents the software architecture that means the various modules making up the system and the dependency. Structure chart representation can be easily implemented using some common programming language. The main focus in the structure chart is on the module
2 min read
Difference between Web Content, Web Structure, and Web Usage Mining
Web mining is an application of the Data Mining technique that is used to find information patterns from the web data. Web Mining helps to improve the power of web search engines by identifying the web pages and classifying web documents. Types of Web Mining : 1. Web Content Mining - Web Content Mining can be used for the mining of useful data, inf
2 min read
Difference between Database and Data Structure
1. Database : A Database is a collection of data that is stored in an organized fashion in a table containing rows and columns using a software package known as Database Management System (DBMS). DBMS is used to modify, define, manipulate and manage data. Some examples of DBMS are : MySQL, Oracle Database and Microsoft Access. 2. Data Structure : I
2 min read
Difference between Control Structure and Control Statement
1. Control Structure :Control Structure, as name suggests, is basically a set of statements and control statements that are controlling their execution. 2. Control Statement :Control Statement, as name suggests, is basically a statement that is used to determine control flow of set of statements. It makes decision on basis of condition provided by
2 min read
Difference between Swift Structures and C Structure
Swift structures are a basic building block in the Swift programming language. They are used to group related data together in a single unit. They are similar to classes, but differ in several key ways, including: Value Types: Structures are value types, meaning that when you pass a structure to a function or assign it to a constant or variable, a
4 min read
Difference between data type and data structure
Data Type A data type is the most basic and the most common classification of data. It is this through which the compiler gets to know the form or the type of information that will be used throughout the code. So basically data type is a type of information transmitted between the programmer and the compiler where the programmer informs the compile
4 min read
Difference between Time Shared Bus, Crossbar Switch &amp; Multiport Memory - Interconnection structure
Prerequisite : Detailed study about the Time Shared Bus, Crossbar Switch &amp; Multiport Memory interconnection structure. Introduction :Interconnection structure can decide the overall system's performance in a multi-processor environment. The processors must be able to share a set of main memory modules &amp; I/O devices in a multiprocessor syste
2 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion and deletion operations are costly in the case of
5 min read
Difference between namespace and class
Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention. It is used as additional information to diffe
2 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Difference between Instance Variable and Class Variable
Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to
2 min read
Difference Between Singleton Pattern and Static Class in Java
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object o
6 min read
Difference Between Abstract Class and Abstract Method in Java
Abstract is the modifier applicable only for methods and classes but not for variables. Even though we don't have implementation still we can declare a method with an abstract modifier. That is abstract methods have only declaration but not implementation. Hence, abstract method declaration should compulsory ends with semicolons. Illustration: publ
3 min read
Difference Between ReadWriteLock Interface and ReentrantReadWriteLock Class in Java
ReadWriteLock is an interface in java. A ReadWriteLock allows us to add a thread-safety feature to a data structure while increasing throughput by allowing multiple threads to read the data concurrently and one thread to update the data exclusively. ReadWriteLock is described in the java.util.concurrent.locks package, with ReentrantReadWriteLock is
3 min read
Difference Between Class.this and this in Java
In java, Class.this and this might refer to the same or different objects depending upon the usage. this this is a reference variable that refers to the current object. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. Class.this Class.this is a reference variable that refers to the
3 min read
Difference Between Object And Class
Class is a detailed description, the definition, and the template of what an object will be. But it is not the object itself. Also, what we call, a class is the building block that leads to Object-Oriented Programming. It is a user-defined data type, that holds its own data members and member functions, which can be accessed and used by creating an
6 min read
Difference between First-Class and Higher-Order Functions in JavaScript
Understanding the difference between first-class and higher-order functions in JavaScript is really important. These are big concepts in programming, especially in the kind of coding used for making websites. This article is all about explaining what they are, how they are used, and why they are so important. 1. First-Class Function A programming l
3 min read
Difference between Shallow and Deep copy of a class
Shallow Copy: Shallow repetition is quicker. However, it's "lazy" it handles pointers and references. Rather than creating a contemporary copy of the particular knowledge the pointer points to, it simply copies over the pointer price. So, each of the first and therefore the copy can have pointers that reference constant underlying knowledge. Deep C
5 min read
Difference between Difference Engine and Analytical Engine
Introduction: The development of computing technology has a rich history, with many inventions and innovations leading to the creation of the modern computer. Two such machines, the Difference Engine and Analytical Engine, were created by the English mathematician and inventor Charles Babbage in the 19th century. While these machines share some sim
7 min read
Difference between Voltage Drop and Potential Difference
Voltage Drop is defined as the decrease in the electric potential along the path of current that is flowing in an electric circuit. Voltage drop can be assigned at each point in the electric circuit that is proportional to the electrical elevation. The amount of energy delivered per second to any component in the circuit is equal to the voltage dro
4 min read
Difference Between Electric Potential and Potential Difference
The flow of electric charges is known as electricity, and it is responsible for producing electric current. An important word associated with electricity is electric potential. A potential difference is required to create the flow of electrons and hence, produce electricity. Before understanding the difference between electric potential and potenti
7 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Java - Inner Class vs Sub Class
Inner Class In Java, one can define a new class inside any other class. Such classes are known as Inner class. It is a non-static class, hence, it cannot define any static members in itself. Every instance has access to instance members of containing class. It is of three types: Nested Inner ClassMethod Local Inner ClassAnonymous Inner Class Genera
3 min read
Differences between Interface and Class in Java
This article highlights the differences between a class and an interface in Java. They seem syntactically similar, both containing methods and variables, but they are different in many aspects. Differences between a Class and an Interface The following table lists all the major differences between an interface and a class in Java language: Class In
4 min read
Differences between Functional Components and Class Components
In this article, we will learn about the differences between functional and class components in React with the help of an example. We will create a counter and implement it using both class and functional components to understand the differences practically. Functional Components Functional components are some of the more common components that wil
4 min read
Differences between ES6 class and ES5 function constructors
In this article, we will discuss the difference between the ES6 class and ES5 function constructors. Both serve the purpose of creating new objects, still, they have some differences between them. ES6 Class constructors: ES6 class constructors work quite the same as class constructors in other object-oriented languages. They are used to create new
2 min read
Article Tags :
Practice Tags :