Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Aptitude
  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • DBMS
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Algorithms
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture
Open In App
Next Article:
What is class Invariant
Next article icon

What is class Invariant

Last Updated : 22 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Overview :
An invariant in Object-Oriented programming refers to some set of conditions or assertions that need to hold throughout the life of an object of a class. These assertions need to hold from the time the constructor is called for an object, at the end of each member (mutator) method call to the end of the destructor call. These conditions verify that an object's behavior is justified during its lifetime and that the object maintains its well-defined state as intended. The invariant, however, need not hold true during the execution of a mutator method but must hold true at the end of it.

Example :
Creating a snake game -
Let's say we were creating a snake game and our snake had the ability to teleport itself a few blocks in some direction. Let us also define our invariant that our snake's head should not cross the playground bounds. Now, if we ensure that our invariant holds at the end of the function where we implement our teleportation ability, we are good. Otherwise, our assertions will fail, and we will find out that there probably is a bug in our code.

Code Implementation in C++ :
As a good programming practice, an invariant private member method is created whose duty is to check that all necessary conditions stay uncompromising and that all methods can make reasonable assumptions about the state of the object. We call this invariant member method at the end of constructors and every mutator method.

Code -

C++
#include <bits/stdc++.h> using namespace std;  // self defined struct to  // hold the position of snake struct Pos {     int x;     int y;     Pos(int _x = 0, int _y = 0)     {         this->x = _x;         this->y = _y;     } };  class Snake { private:     int play_width; // right bound     int play_height; // height bound     Pos loc; // position of snake's head     void Invariant()     {         assert(loc.x >= 0 && loc.x <= play_width);         assert(loc.y >= 0 && loc.y <= play_height);     } public:     // initialise the snake object with _width ans _height bounds     // ans posx, posy current position     Snake(int _width, int _height, Pos _p)     {         this->play_width = _width;         this->play_height = _height;         this->loc.x = _p.x;         this->loc.y = _p.y;         // call the invariant to ensure the object         // was constructed correctly         Invariant();     }      // teleport and add inc.x units to current X coordinate     // ans inc.y units to Y coordinate of snake      void TeleportAhead(Pos inc)       {         loc.x += inc.x;         loc.y += inc.y;         //ensure that our snake wasn't          // teleported out of play bounds         Invariant();     }      // return current position     // calling invariant is unnecessary     // because this is an accessor method     Pos GetLoc()     {         return loc;     } };    int main() {     Snake snek(30, 20, Pos(5, 5));      // will throw assert error because     // our snake is teleported out of bound     snek.TeleportAhead(Pos(20, 20));      // will also fail Invariant() assertion     // because the snake is being spawned out     // of bounds     Snake snek2(10, 10, Pos(12, 8));     return 0; } 

Next Article
What is class Invariant

A

ayush.verma16
Improve
Article Tags :
  • Misc
  • GATE CS
  • Object-Oriented-Design
Practice Tags :
  • Misc

Similar Reads

    is_class template in C++
    The std::is_class template of C++ STL is used to check whether the given type is class or not. It returns a boolean value showing the same. Syntax: template <class T> struct is_class; Parameter: This template accepts single parameter T (Trait class) to check whether T is a class or not. Return
    2 min read
    Invariant in TypeScript
    An invariant is a situation that does not change or alter all the time the program runs. It works as an assurance or limitation on the state of an object, data structure, or system. Invariants make sure that specific properties are maintained all the time which also prevents any abrupt behaviors and
    3 min read
    Loop Invariant Condition with Examples
    Definition: A loop invariant is a condition [among program variables] that is necessarily true immediately before and immediately after each iteration of a loop. (Note that this says nothing about its truth or falsity part way through an iteration.) A loop invariant is some predicate (condition) tha
    7 min read
    Object Class in Java
    Object class in Java is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any other class then it is a direct child class of the Java Object class and if it extends another class then it is indirectly derived. The Ob
    7 min read
    java.lang.MethodType Class in Java
    MethodType is a Class that belongs to java.lang package. This class consists of various types of methods that help in most of cases to find the method type based on the input object, or parameters of the method. All the instances of methodType are immutable. This means the objects of the methodType
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences