Object-Oriented Programming: Dynamic Memory. Copy Constructor, Destructor (2/2)

In our C tutorial we've covered dynamic memory management.  This reffers to manually allocating and freeing memory using available functions from the standard library.  In C, we used the malloc, calloc and free functions.  These functions are also included in the C++ programming language for compatibility, but C++ provides similar functionality (recommended by the language's authors) with the new and delete operators.

The new operator is used for allocating memory.  To allocate a single variable dynamically, we use the scalar (non-array) form of the new operator:

int *ptr = new int; // dynamically allocate an integer and assign the address to ptr
Of course, this works the same way for any data type (including user-defined types and objects of user-defined classes).  It is also possible to allocate a block (array) of elements of a certain type, just like with malloc and calloc:
type *ptr = new type[n];
Our pointer now points to a valid block of memory with space for n elements of type type.

 

In some rare cases when the operating system doesn't have any memory to grant our request with, the attempt of allocation fails.  This is why we usually perform a check which would detect a failure:

if (ptr == nullptr) 
{
  //error assigning memory
}

 

Of course, when we are done using dynamically allocated memory, we need to explicitly tell the program to free that memory.  This is performed with the delete operator.  This operator doesn't actually delete anything, it just returns that memory to the operating system, which then reassigns it.

The syntax of the delete operator is:

delete ptr;

delete[] ptrToArray;
The first statement releases the memory of a single element allocated using new, and the second one releases the memory allocated for arrays of elements using new type[n].

 

Now, let's see how we can use new and delete to write a copy constructor and destructor, which we talked about last time:

class MyString
{

public:

        char* str;

	//constructor
	MyString(char *myStr)
	{
		str = new char[strlen(myStr)+1];
		strcpy(str, myStr); //standard library function for copying from one string to another
	}

        //copy constructor
	MyString(const MyString &strObj)
	{
		str = new char[strlen(strObj.str)+1];
		strcpy(str, strObj.str);
	}

	//destructor
	~MyString()
	{
		delete str;
	}
};

int main()
{
	MyString ms1("Programming");
	MyString ms2(ms1);

	cout << ms2.str << endl; //"Programming" written

	return 0;
}

 

This example shows us an application of what we've learned in the previous article - copy constructor, deep copy of the MyString object, and the destructor.  As we can see, we initialized the ms2 object with our first object - we created a deep copy.  The final step in writing our class would be overloading the assignment operator, which we will learn soon.

Online sample: http://goo.gl/TT783t

Thought For The Day

“Nothing is a waste of time if you use the experience
wisely.”
Auguste Rodin

 

 

4 Budgeting Blunders to Avoid

In a recent post, we identified the best ways to start a budget and manage your money better.  If you’ve started that process, congratulations!  You’re on the path to financial wellbeing.  However, before you get too far into your new fiscally responsible lifestyle, we wanted to offer you some suggestions on how to avoid common budgeting blunders:

  1. Not Putting Savings First.  A lot of people will figure out their main expenses and then put what is left over into savings.  However, experts recommend that you determine a savings goal first and then, try to cut your expenditures (food and entertainment, for example) down so you can meet your savings goal.
  2. Not Being Realistic.  It’s tempting when you’re first making a budget to have an idealized vision of how you’ll live after the budget is in place.  However, if you are too strict with yourself, you’re far more likely to splurge in a category and get discouraged about your inability to adhere to your budget.  While you probably don’t want to be excessively generous with yourself, you also don’t want to be too miserly.
  3. Not Considering the True Cost.  When contemplating a major purchase—like a house or a car—people often forget to calculate the true cost of ownership.  Let’s say, for example, that you don’t currently own a car and that you take the bus to get to your job.  Were you to purchase a car, not only would you want to budget for the cost of your new car payment, but you would also want to account for car insurance, gas prices, car maintenance and repair, parking expenses, and roadside assistance memberships.
  4. Not Planning for Annual or Quarterly Expenses.  It’s easy to forget about those annual and quarterly expenses—Christmas and taxes immediately come to mind but you may have others.  When planning your budget, you may want to review bank statements from the previous year to make sure that you haven’t overlooked something important so you can stash some money aside.

How to Become More Mindful

In a previous blog post, we discussed all of the reasons that mindfulness is such a valuable skill in the workplace—it improves concentration, reduces stress, prevents burnout, and increases productivity.  And those benefits are just the work-related ones!  Mindfulness has also been associated with higher quality relationships, greater contentment, and better immune function.  Furthermore, studies have shown that mindfulness can help with fertility, high blood pressure, and inflammation.    

If you’re eager to benefit from the practice of mindfulness, we have some tips to help you get started:

  • Practice Mindful Breathing.  You can set aside specific time for this activity—for example, 10 minutes when you first wake up—or you can turn to mindful breathing throughout the day.  Simply spend time focusing on your breathing, as you slowly inhale and exhale.  Ignore any distracting thoughts and continue to turn your attention to your breath as you relax.
  • Focus on a Single Task.  Today it’s very common for people to multitask, never really giving their full attention to a specific task.  Instead, experts recommend that you do 1 thing at a time and when you engage in the activity, focus on it entirely--even if it’s something as mundane as doing the dishes or brushing your teeth.
  • Accept your Feelings.  Have you ever heard the phrase, “What you resist, persists”?  Mindfulness isn’t about being happy all of the time.  Instead, people who practice mindfulness allow themselves to experience their feelings, even when those feelings are negative.  By nonjudgmentally sitting with their unpleasant feelings, their negative feelings pass more quickly.  This allows mindful people to return to a happier state sooner than those who repress or ignore their feelings.
  • Go for a Walk.  Think of a walk as meditation in nature.  The act of walking can relieve stress, inspire creative ideas, and enhance your mood.  

5 Books Every Entrepreneur Should Read

If you own your own business, you know that sometimes it can be difficult to deal with all of the challenges that arise.  That’s why it’s often helpful to turn to the experts—many times they’ve been there themselves and can offer guidance on how to achieve success while minimizing pitfalls along the way.  To that end, we have 5 book recommendations that are especially helpful for entrepreneurs:

  1. The Lean Startup: How Today’s Entrepreneurs Use Continuous Innovation to Create Radically Successful Businesses by Eric Ries – Currently the #1 bestseller in Amazon’s Entrepreneur category, this book offers a methodology for creating a successful startup and offers plenty of real-life, interesting examples.

  2. The Four-Hour Workweek by Timothy Ferriss – This book is a great inspirational read and while a 4-hour workweek is probably a stretch for most of us, Ferriss includes some great ideas for automating work flow, outsourcing, and managing time more efficiently.

  3. The Innovator’s Dilemma by Clayton M. Christensen – This book is a favorite of Jeff Bezos, Amazon founder and CEO, as well as many other startup founders.  It identifies the reason why companies that seemingly do everything right become ‘dinosaurs,’ and it offers guidance on how other companies can avoid similar fates.

  4. How to Win Friends and Influence People by Dale Carnegie – Although this bestselling book’s target audience isn’t entrepreneurs, it’s still a useful read.  The book offers various techniques for handling other people which is useful for entrepreneurs trying to generate sales, manage employees, deal with suppliers, etc.  First published in 1937, this book has gone on to sell over 15 million copies and even today, it is the number 1 bestselling book in Amazon’s Business Leadership category.

  5. Thinkertoys: A Handbook of Creative-Thinking Techniques by Michael Michalko – The ability to deal creatively with problems, as well as develop innovative ideas, is important for any entrepreneur.  This book will guide you to think more creatively by teaching you how to approach problems in unconventional ways.